This is Thread-Safe right?

前端 未结 6 981
日久生厌
日久生厌 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条回答
  •  暖寄归人
    2020-12-14 15:04

    Define thread safe.

    If you want to ensure that _count will never be greater than MAXIMUM, than you did not succeed.

    What you should do is lock around that too:

    private int _count;
    private object locker = new object();
    
    public void CheckForWork() 
    {
        lock(locker)
        {
            if (_count >= MAXIMUM) return;
            _count++;
        }
        Task.Run(() => Work());
    }
    
    public void CompletedWorkHandler() 
    {
        lock(locker)
        {
            _count--;
        }
        ...
    }
    

    You might also want to take a look at The SemaphoreSlim class.

提交回复
热议问题