C# manual lock/unlock

前端 未结 5 2250
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 08:25

I have a function in C# that can be called multiple times from multiple threads and I want it to be done only once so I thought about this:

class MyClass
{
          


        
5条回答
  •  感动是毒
    2020-12-01 08:38

    You can check the value of done before and after the lock:

        if (!done)
        {
            lock(this)
            {
                if(!done)
                {
                    done = true;
                    _DoSomething();
                }
            }
        }
    

    This way you won't enter the lock if done is true. The second check inside the lock is to cope with race conditions if two threads enter the first if at the same time.

    BTW, you shouldn't lock on this, because it can cause deadlocks. Lock on a private field instead (like private readonly object _syncLock = new object())

提交回复
热议问题