问题描述
我有此功能,每分钟都会调用一次,有时它会在代码中以其他方式触发。
static async Task WriteFileAsync(string file,string content)
{
using (StreamWriter outputFile = new StreamWriter(file))
{
await outputFile.WriteAsync(content);
}
}
System.IO.IOException: 'The process cannot access the file 'hello.json' because it is being used by another process.'
解决方法
您需要具有锁以防止多个线程同时调用WriteFileAsync
。由于当块中存在lock
状态时,无法使用await
关键字SemaphoreSlim。
// Initialize semaphore (maximum threads that can concurrently access the file is 1)
private static readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1,1);
static async Task WriteFileAsync(string file,string content)
{
// Acquire lock
await _semaphoreSlim.WaitAsync();
try
{
using (StreamWriter outputFile = new StreamWriter(file,true))
{
await outputFile.WriteAsync(content);
}
}
finally
{
// Release lock in finally block so that lock is not kept if an exception occurs
_semaphoreSlim.Release();
}
}