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

后端 未结 7 1388
失恋的感觉
失恋的感觉 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:40

    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();
        }
    }
    

提交回复
热议问题