Using lock statement within a loop in C#

前端 未结 3 1877
小鲜肉
小鲜肉 2020-12-12 18:42

Lets take the sample class SomeThread where we are attempting to prevent the DoSomething methods from being called after the Running property is set to false and Dispose is

3条回答
  •  -上瘾入骨i
    2020-12-12 19:20

    Check Running again inside the lock:

    while (Running)
    {
        lock(locker)
        {
            if(Running) {
                DoSomething1();
                DoSomething2();
            }
        }
    }
    

    You could even rewrite this as a while(true)...break, which would probably be preferable.

提交回复
热议问题