Metro App FileIO.WriteTextAsync Multiple Threads

馋奶兔 提交于 2019-12-05 09:31:25

You can use SemaphoreSlim to act as an async-compatible lock:

SemaphoreSlim _mutex = new SemaphoreSlim(1);

async Task MyMethodAsync()
{
  await _mutex.WaitAsync();
  try
  {
    ...
  }
  finally
  {
    _mutex.Release();
  }
}

Personally, I don't like the finally, so I usually write my own IDisposable to release the mutex when disposed, and my code can look like this:

async Task MyMethodAsync()
{
  // LockAsync is an extension method returning my custom IDisposable
  using (await _mutex.LockAsync()) 
  {
    ...
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!