c0D*_*g1c 5 locking windows-runtime .net-4.5 winrt-async
我有一个从多个线程经常调用的方法.它涉及使用写入磁盘await FileIO.WriteTextAsync
.从单个线程调用它时工作正常,但是一旦我开始在多个线程中执行此操作,我会收到此错误:
The process cannot access the file because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)
我知道错误意味着什么,但我不知道如何解决它.通常,我会创建一个lock(object)
语句,以确保一次只有一个线程访问该文件.但是,这是一个异步方法,因此我不能await
在lock(object)
语句的主体中使用运算符.
请告知如何处理此方案.
您可以使用SemaphoreSlim
它作为async
兼容锁:
SemaphoreSlim _mutex = new SemaphoreSlim(1);
async Task MyMethodAsync()
{
await _mutex.WaitAsync();
try
{
...
}
finally
{
_mutex.Release();
}
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我不喜欢finally
,所以我通常会自己编写,以便IDisposable
在处理时释放互斥锁,我的代码看起来像这样:
async Task MyMethodAsync()
{
// LockAsync is an extension method returning my custom IDisposable
using (await _mutex.LockAsync())
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
685 次 |
最近记录: |