I need to create a Thread-safe static variable in

2019-01-25 08:42发布

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.

7条回答
我想做一个坏孩纸
2楼-- · 2019-01-25 09:20

You can also use the ReaderWriterLockSlim, that is more efficient for multiple reads and less writes:

static int needsToBeThreadSafe = 0;
static System.Threading.ReaderWriterLockSlim rwl = new System.Threading.ReaderWriterLockSlim();

public static void M1()
{
    try
    {
        rwl.EnterWriteLock();
        needsToBeThreadSafe = RandomNumber();
    }
    finally
    {
        rwl.ExitWriteLock();
    }

}

public static void M2()
{
    try
    {
        rwl.EnterReadLock();
        print(needsToBeThreadSafe);
    }
    finally
    {
        rwl.ExitReadLock();
    }
}
查看更多
登录 后发表回答