I want async write log in asp.net mvc,the code is like this:
public ActionResult Index()
{
byte[] buffer = Encoding.UTF8.GetBytes(string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine));
FileStream fs = new FileStream(@"c:\log.txt", FileMode.Append, FileAccess.Write, FileShare.Write, 1024, true);
fs.BeginWrite(buffer, 0, buffer.Length, ar =>
{
fs.EndWrite(ar);
fs.Close();
}, null);
}
But the result is not I expected, some log not be recorded,can anyone tell me what’s wrong with the code
You need to ensure that only one thread is writing to the file. If you have 2 concurrent users calling the Index action at the same time chances are they will try to write to the log file at the same time and the second will fail. In a multithreaded applications such as ASP.NET always make sure that you are properly synchronizing access to shared resources.
Also in your code you are not guarding against errors. What if an exception is thrown? You never close this stream and the second attempt to access it will throw an exception.
So one possibility to simplify this code is to use the TPL:
and to avoid such noise and pollution in your controllers you could use action filters:
and then:
But instead of reinventing wheels I would recommend you using the tracing capabilities built into the .NET framework.