Use Environment.CurrentManagedThreadId instead of Thread.CurrentThread.ManagedThreadId
Use Environment.CurrentManagedThreadId instead of Thread.CurrentThread.ManagedThreadId
Microsoft docsDescription
System.Environment.CurrentManagedThreadId is a compact and efficient replacement of the Thread.CurrentThread.ManagedThreadId pattern.
Cause
Using Thread.CurrentThread.ManagedThreadId for getting the current managed thread ID instead of System.Environment.CurrentManagedThreadId.
How to fix violations
The violation can either be fixed manually, or, in some cases, using Quick Actions to fix code in Visual Studio.
The following two code snippets show a violation of the rule and how to fix it: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use 'Environment.CurrentManagedThreadId' from the list of options that's presented. !Code fix for CA1840 - Use 'Environment.CurrentManagedThreadId'
Example
using System.Threading;
class MyClass
{
void MyMethod()
{
int id = Thread.CurrentThread.ManagedThreadId; // Violation occurs
}
}When to suppress
It's safe to suppress a violation of this rule if you're not concerned about the performance impact from using Thread.CurrentThread.ManagedThreadId.