c# - 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.'
解决方案
你需要有一个锁来防止多个线程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();
}
}
推荐阅读
- vue.js - 在 Vue js 中使用 v-show 属性显示/隐藏元素
- selenium - 如何使用 selenium webdriver(eclipse)单击下拉菜单(不是由 select 创建的)?
- python - 如何使用 Python 查询小型数据集
- typescript - 从类型中提取调用签名
- ios - Fabric 不会显示我的 Firebase 应用程序
- java - 杰克逊可以以不区分大小写的方式检查重复的属性吗?
- c# - 访问存储在 .net Core cookie 中的数据
- javascript - http策略的validate方法中如何访问请求url?
- sql-server - 来自 2 个表的数据要发送到 excel 文件
- python-3.x - 在 Python 中创建 jTDS 连接字符串