Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

ok, its a little more complicated than the question.

class A
{
   static int needsToBeThreadSafe = 0;

   public static void M1()
   {
     needsToBeThreadSafe = RandomNumber();
   }

   public static void M2()
   {
     print(needsToBeThreadSafe);
   }
}

now i require that between M1() and M2() calls 'needsToBeThreadSafe' stays Thread Safe.

like image 555
Storm Avatar asked Aug 10 '09 13:08

Storm


1 Answers

How About:

public static void M1()
{
    Interlocked.Exchange( ref needsToBeThreadSafe, RandomNumber() );
}

public static void M2()
{
    print( Interlocked.Read( ref needsToBeThreadSafe ) );
}
like image 111
cosmo Avatar answered Oct 21 '22 22:10

cosmo