I need to create a Thread-safe static variable in C# .Net

后端 未结 7 1378
失恋的感觉
失恋的感觉 2020-12-17 18:01

ok, its a little more complicated than the question.

class A
{
   static int needsToBeThreadSafe = 0;

   public static void M1()
   {
     needsToBeThreadSa         


        
相关标签:
7条回答
  • 2020-12-17 18:41

    To start with I agree with the answers using lock(), that is the safest way.

    But there exists a more minimalist approach, your sample code only shows single statements using needsToBeThreadSafe and since int is atomic you only need to prevent caching by the compiler using volatile:

    class A
    {
       static volatile int needsToBeThreadSafe = 0;
    
    }
    

    But if you need needsToBeThreadSafe to be 'ThreadSafe' over multiple statements, use a lock.

    0 讨论(0)
提交回复
热议问题