Metro App FileIO.WriteTextAsync 多线程 [英] Metro App FileIO.WriteTextAsync Multiple Threads
问题描述
我有一个从多个线程频繁调用的方法.它涉及使用 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屋!