With threads you could use Semaphore, mutex, ManualResetEvent, etc... to sync a shared data, how do you accomplish the same thing with tasks? Essentially, if I have shared data between different tasks that run on the thread pool with Task.run() or that resume on the thread pool on a random thread after an async event, how would I sync them up if they share data?
1 Answer
You need a lock that allows you to await it rather than block. This functionality is offered by the SemaphoreSlim class.
SemaphoreSlim _semaphore = new SemaphoreSlim(1);
async Task HandleLockedResource()
{
await _semaphore.WaitAsync();
try
{
await DoSomethingWithLockedResource();
}
finally
{
_semaphore.Release();
}
}
See also How to combine async with locking and What is the best practice using async in lock
Task.WhenAll.