How to a synchronize tasks?

徘徊边缘 提交于 2019-12-20 10:11:59

问题


Say I have an async method which saves to file:

async Task SaveToFileAsync()
{
   var file = await folder.GetFileAsync ( ...)
   var stream = file.OpenFileAsync(...)
   ///etc

}

Now imagine that SaveToFileAsync is called twice simultaneously. This is a problem because you can't write on the same file simultaneously

If this were a regular method, lock() would fix this:

void SaveToFile()
{
   lock(something)
   {
      /// code here
   }
}

However, lock is not allowed in an async method.

Of course, one could call Monitor.Enter() or use a mutex but these objects work with threads, not tasks. Therefore they are not the answer.

So since lock() is not an option, how can synchronize multiple tasks? In particular, what code should I write to ensure that "SaveToFileAsync" is called only once at a time?


回答1:


For an async mutual exclusion mechanism, have a look at

    Building Async Coordination Primitives, Part 6: AsyncLock

You could use the AsyncLock class follows:

private readonly AsyncLock m_lock = new AsyncLock();

async Task SaveToFileAsync()
{
    using (await m_lock.LockAsync()) 
    { 
        var file = await folder.GetFileAsync(...);
        var stream = await file.OpenFileAsync(...);
        // etc
    }
}


来源:https://stackoverflow.com/questions/10128345/how-to-a-synchronize-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!