CA2024:请勿在异步方法中使用 StreamReader.EndOfStream

财产 价值
规则 ID CA2024
游戏 请勿在异步方法中使用 StreamReader.EndOfStream
类别 可靠性
修复中断或非中断性 非中断
默认情况下,在 .NET 10 中启用 作为警告

原因

StreamReader.EndOfStream 的调用是在异步方法中进行的。

规则说明

如果未缓冲任何数据,则属性 StreamReader.EndOfStream 可能会导致意外同步阻塞。 而是直接使用 StreamReader.ReadLineAsync(),在到达流的末尾时返回 null

如何解决冲突

若要修复冲突,请直接调用 StreamReader.ReadLineAsync() 并检查 null的返回值。

以下代码片段显示了 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

以下代码片段修复了冲突:

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

何时禁止显示警告

不应禁止显示此规则中的警告,因为如果你未修复违规,应用可能会挂起。

禁止显示警告

如果只想取消单个冲突,请将预处理器指令添加到源文件以禁用,然后重新启用规则。

#pragma warning disable CA2024
// The code that's violating the rule is on this line.
#pragma warning restore CA2024

若要禁用文件、文件夹或项目的规则,请将其严重性设置为 配置文件中的 none

[*.{cs,vb}]
dotnet_diagnostic.CA2024.severity = none

有关详细信息,请参阅 如何取消代码分析警告