A call to StreamReader.EndOfStream is made inside an async method.
Rule descriptionThe property StreamReader.EndOfStream can cause unintended synchronous blocking when no data is buffered. Instead, use StreamReader.ReadLineAsync() directly, which returns null
when reaching the end of the stream.
To fix a violation, directly call StreamReader.ReadLineAsync() and check the return value for null
.
The following code snippet shows a violation of CA2024:
public async Task Example(StreamReader streamReader)
{
while (!streamReader.EndOfStream)
{
string? line = await streamReader.ReadLineAsync();
// Do something with line.
}
}
Public Async Function Example(streamReader As StreamReader) As Task
While Not streamReader.EndOfStream
Dim line As String = Await streamReader.ReadLineAsync()
' Do something with line.
End While
End Function
The following code snippet fixes the violation:
public async Task Example(StreamReader streamReader)
{
string? line;
while ((line = await streamReader.ReadLineAsync()) is not null)
{
// Do something with line.
}
}
Public Async Function Example(streamReader As StreamReader) As Task
Dim line As String = Await streamReader.ReadLineAsync()
While line IsNot Nothing
' Do something with line.
line = Await streamReader.ReadLineAsync()
End While
End Function
When to suppress warnings
You shouldn't suppress warnings from this rule, as your app might hang if you don't fix the violations.
Suppress a warningIf you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA2024
// The code that's violating the rule is on this line.
#pragma warning restore CA2024
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2024.severity = none
For more information, see How to suppress code analysis warnings.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4