C#异步文件在随机时间写入System.IO.IOException

问题描述

我有功能,每分钟都会调用一次,有时它会在代码中以其他方式触发。

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...