【问题标题】:c# async filewrite System.IO.IOException at random timesc# async filewrite System.IO.IOException at random time
【发布时间】:2020-08-23 10:58:13
【问题描述】:

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

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的方法,你应该等待WriteFileAsync

标签: c# .net multithreading asynchronous


【解决方案1】:

你需要有一个锁来防止多个线程同时调用WriteFileAsync。由于在块中有await 状态时不能使用lock 关键字,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();
    }
}

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 2011-03-14
    • 2015-09-28
    • 1970-01-01
    • 2010-12-12
    相关资源
    最近更新 更多