【发布时间】:2017-08-10 16:03:42
【问题描述】:
我有一个异步写入日志文件的函数,该函数被多次调用。但是,我收到一个错误:
System.IO.IOException: 'The process cannot access the file '<log path>' because it is being used by another process.'
代码在这里:
public async void log(string msg)
{
await Task.Run(() => {
// Check that log directory exists, or create one
if (!Directory.Exists(@"log dir")) Directory.CreateDirectory(@"log dir");
// Append to log
using (StreamWriter w = File.AppendText(@"log path"))
{
w.WriteLine(DateTime.Now + " : " + msg);
w.Close();
}
});
}
我对异步编程的理解主要来自node.js,它是一种单线程语言。我是否认为由于 C# 是多线程的(并且对异步代码采用多线程方法),所以 IO 不会像在 node.js 中那样自动排队等待资源?
有没有一种简单的方法可以在 C# 中异步写入文件?或者我最好让这个日志函数同步,因为性能成本与几行写入无关......
【问题讨论】:
-
我的想法是触发并忘记日志行。但我想他们应该在代码中等待。在这种情况下避免碰撞
-
你为什么不用支持异步的日志框架nuget.org/packages/Log4Net.Async
标签: c# asynchronous io