Search code examples
c#multithreadingthread-safetyinterlocked

This is Thread-Safe right?


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

Both methods are accessed by multiple threads.

private int _count;

public void CheckForWork() {
    if (_count >= MAXIMUM) return;
    Interlocked.Increment(ref _count);
    Task t = Task.Run(() => Work());
    t.ContinueWith(CompletedWorkHandler);
}

public void CompletedWorkHandler(Task completedTask) {
    Interlocked.Decrement(ref _count);
    // Handle errors, etc...
}

Solution

  • No, if (_count >= MAXIMUM) return; is not thread safe.

    edit: You'd have to lock around the read too, which should then logically be grouped with the increment, so I'd rewrite like

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