共用方式為


CA2024:請勿在異步方法中使用 StreamReader.EndOfStream

財產 價值
規則標識碼 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

如需詳細資訊,請參閱 如何在隱藏程式代碼分析警告。