CA1840:使用「Environment.CurrentManagedThreadId」而非「Thread.CurrentThread.ManagedThreadId」

屬性
規則識別碼 CA1840
職稱 使用 Environment.CurrentManagedThreadId,而不是 Thread.CurrentThread.ManagedThreadId
類別 效能
修正是造成中斷還是不中斷 不中斷
在 .NET 10 中預設啟用 作為建議
適用語言 C# 與 Visual Basic

原因

使用 Thread.CurrentThread.ManagedThreadId 取得目前的受控線程識別碼,而不是 System.Environment.CurrentManagedThreadId

規則描述

System.Environment.CurrentManagedThreadIdThread.CurrentThread.ManagedThreadId 模式的精簡高效的替代品。

如何修正違規

違規可以手動修正,或在某些情況下,使用快速動作修正Visual Studio中的程式碼。

下列兩個代碼段顯示違反規則,以及如何修正它:

using System.Threading;

class MyClass
{
    void MyMethod()
    {
        int id = Thread.CurrentThread.ManagedThreadId; // Violation occurs
    }
}
Imports System.Threading

Class MyClass
    Private Sub MyMethod()
        Dim id As Integer = Thread.CurrentThread.ManagedThreadId ' Violation occurs.
    End Function
End Class
using System.Threading;

class MyClass
{
    void MyMethod()
    {
        int id = System.Environment.CurrentManagedThreadId; // Violation fixed
    }
}
Imports System.Threading

Class MyClass
    Private Sub MyMethod()
        Dim id As Integer = System.Environment.CurrentManagedThreadId ' Violation fixed.
    End Function
End Class

提示

在 Visual Studio 中,可以使用針對此規則的程式碼修正。 若要使用它,請將游標放在違規上,然後按 Ctrl+。(句號)。 從所呈現的選項清單中,選擇 「使用 'Environment.CurrentManagedThreadId'」

CA1840 的程序代碼修正 - 使用 'Environment.CurrentManagedThreadId'

隱藏警告的時機

如果您不擔心使用 Thread.CurrentThread.ManagedThreadId的效能影響,則隱藏此規則的違規是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或專案的規則,請在組態檔中將其嚴重性設為 none

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

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

另請參閱