I have this function that is called every minute and sometimes it is triggered other ways in the code.
static async Task WriteFileAsync(string file, string content)
{
using (StreamWriter outputFile = new StreamWriter(file))
{
await outputFile.WriteAsync(content);
}
}
Sometimes I get this error, but not always, it is quite random.
System.IO.IOException: 'The process cannot access the file 'hello.json' because it is being used by another process.'
You need to have a lock to prevent multiple threads from calling WriteFileAsync
simultaneously. Since lock
keyword cannot be used when there is an await
statmeent in the block, 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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.