iJa*_*ade 9 c# asp.net deadlock
这是我的日志写入功能:
public static void WriteLog(string source, string message)
{
string logFilePath = @"C:\LogFile\log.txt";
using (StreamWriter sw = new StreamWriter(logFilePath, true))
{
sw.Write(source + ": :" + message);
}
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码有时会导致我错误:
该进程无法访问该文件,因为该文件正由另一个进程使用
所以我修改了我的代码,这是我的新代码:
public static void WriteLog(string source, string message)
{
object _lock = new object();
lock (_lock)
{
string logFilePath = @"C:\LogFile\log.txt";
using (StreamWriter sw = new StreamWriter(logFilePath, true))
{
sw.Write(source + ": :" + message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我在使用此代码后没有收到错误.但我仍然想知道这是否正确使用锁来防止由于死锁导致的错误,以及我使用锁的方式是否正确.
Llo*_*oyd 22
在第二个示例中使用锁定无论如何都无法正常工作,因为您每次都会创建一个新的锁定对象并将其锁定.
你真正想要文件明智的是这样的:
public static void WriteLog(string source, string message)
{
string logFilePath = @"C:\LogFile\log.txt";
using (FileStream file = new FileStream(logFilePath,FileMode.Append,FileAccess.Write,FileShare.None))
{
StreamWriter writer = new StreamWriter(file);
writer.write(source + ": : " + message);
file.Flush();
file.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
这应该专门锁定文件,而你写完BUT正确关闭文件一旦完成.
这不能解决线程问题,因为两个线程仍然可以冲突.如果一个线程锁定文件,则后续请求将失败.
要使用锁定解决此问题,请将锁定对象移动到所有线程可以共享和锁定的静态,例如:
public static class Logger
{
private static object locker = new object();
public static void Log(string source, string message)
{
lock (locker)
{
string logFilePath = @"C:\LogFile\log.txt";
using (FileStream file = new FileStream(logFilePath,FileMode.Append,FileAccess.Write,FileShare.None))
{
StreamWriter writer = new StreamWriter(file);
writer.write(source + ": : " + message);
writer.Flush();
file.Close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将导致后续线程等到锁变为可用,然后再按原始预期写入文件.
注意Oded的评论,但仍适用于此方法.