Skip to content

Commit 7678d09

Browse files
double checked locking for AdditionalTextFile.GetText (#41383)
* Add double checked locking for AdditionalTextFile.GetText. * Use LazyInitializer * Use Lazy instead of LazyInitializer * Make _text readonly
1 parent fdfac66 commit 7678d09

File tree

1 file changed

+11
-17
lines changed

1 file changed

+11
-17
lines changed

src/Compilers/Core/Portable/AdditionalTextFile.cs

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,9 @@ internal sealed class AdditionalTextFile : AdditionalText
1919
{
2020
private readonly CommandLineSourceFile _sourceFile;
2121
private readonly CommonCompiler _compiler;
22-
private SourceText? _text;
22+
private readonly Lazy<SourceText?> _text;
2323
private IList<DiagnosticInfo> _diagnostics;
2424

25-
private readonly object _lockObject = new object();
26-
2725
public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler)
2826
{
2927
if (compiler == null)
@@ -34,6 +32,15 @@ public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compi
3432
_sourceFile = sourceFile;
3533
_compiler = compiler;
3634
_diagnostics = SpecializedCollections.EmptyList<DiagnosticInfo>();
35+
_text = new Lazy<SourceText?>(ReadText);
36+
}
37+
38+
private SourceText ReadText()
39+
{
40+
var diagnostics = new List<DiagnosticInfo>();
41+
var text = _compiler.TryReadFileContent(_sourceFile, diagnostics);
42+
_diagnostics = diagnostics;
43+
return text;
3744
}
3845

3946
/// <summary>
@@ -45,20 +52,7 @@ public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compi
4552
/// Returns a <see cref="SourceText"/> with the contents of this file, or <c>null</c> if
4653
/// there were errors reading the file.
4754
/// </summary>
48-
public override SourceText GetText(CancellationToken cancellationToken = default)
49-
{
50-
lock (_lockObject)
51-
{
52-
if (_text == null)
53-
{
54-
var diagnostics = new List<DiagnosticInfo>();
55-
_text = _compiler.TryReadFileContent(_sourceFile, diagnostics);
56-
_diagnostics = diagnostics;
57-
}
58-
}
59-
60-
return _text;
61-
}
55+
public override SourceText? GetText(CancellationToken cancellationToken = default) => _text.Value;
6256

6357
/// <summary>
6458
/// Errors encountered when trying to read the additional file. Always empty if

0 commit comments

Comments
 (0)