Metro App FileIO.WriteTextAsync多线程 [英] Metro App FileIO.WriteTextAsync Multiple Threads

查看:83
本文介绍了Metro App FileIO.WriteTextAsync多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个经常从多个线程调用的方法.它涉及使用await FileIO.WriteTextAsync写入磁盘.从单个线程调用它时,它的工作效果很好,但是一旦我在多个线程中开始执行此操作,就会收到此错误:

I have a method which is called frequently from multiple threads. It involves writing to disk using await FileIO.WriteTextAsync. This works fine when it is called from a single thread, but once I start doing this in multiple threads, I get this error:

The process cannot access the file because it is being used by another process.

我知道错误的含义,但是我不确定如何解决.通常,我将创建一个lock(object)语句,以确保一次仅由一个线程访问该文件.但是,这是一个异步方法,因此我不能在lock(object)语句的主体中使用await运算符.

I know what the error means, but I'm not sure how to work around it. Normally, I would create a lock(object) statement, to ensure that the file is being accessed by only one thread at a time. However, this is an asynchronous method and as such I can't use the await operator in the body of the lock(object) statement.

请提供有关如何处理这种情况的建议.

Please advise on how to handle this scenario.

推荐答案

您可以使用SemaphoreSlim充当async兼容的锁:

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();
  }
}

我个人不喜欢finally,所以我通常编写自己的IDisposable以便在处置时释放互斥量,并且我的代码可以如下所示:

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()) 
  {
    ...
  }
}

这篇关于Metro App FileIO.WriteTextAsync多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆