首页 > 解决方案 > c# async filewrite System.IO.IOException at random time

问题描述

我有这个每分钟调用一次的函数,有时它会在代码中以其他方式触发。

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.'

标签: c#.netmultithreadingasynchronous

解决方案


你需要有一个锁来防止多个线程WriteFileAsync同时调用。由于在块中lock有状态时不能使用关键字awaitSemaphoreSlim 。

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

推荐阅读