This is Thread-Safe right?

前端 未结 6 985
日久生厌
日久生厌 2020-12-14 14:40

Just checking... _count is being accessed safely, right?

Both methods are accessed by multiple threads.

private int _count;

public void         


        
6条回答
  •  旧时难觅i
    2020-12-14 15:03

    you can do the following if you don't want to lock or move to a semaphore:

    if (_count >= MAXIMUM) return; // not necessary but handy as early return
    if(Interlocked.Increment(ref _count)>=MAXIMUM+1)
    {
        Interlocked.Decrement(ref _count);//restore old value
        return;
    }
    Task.Run(() => Work());
    

    Increment returns the incremented value on which you can double check whether _count was less than maximum, if the test fails then I restore the old value

提交回复
热议问题