0

我想在跨线程中访问并编写一个 txt 文件,但软件给出了一个例外,因为多个线程想要同时访问同一个文件。如何调用 streamwriter 以避免异常?这是我的代码:

void WriteLog(string LogStr)
{
    StreamWriter sw = new StreamWriter("Log.txt", true);
    sw.WriteLine(LogStr);
    sw.Close();
}

我在线程中调用 WriteLog 方法。

谢谢你。

4

3 回答 3

2

您可以尝试使用互斥锁:

private Mutex mut = new Mutex(); // Somewhere in mail class
void WriteLog(string LogStr)
{
    mut.WaitOne();
    try 
    {
        using(StreamWriter sw = new StreamWriter("Log.txt", true))
            sw.WriteLine(LogStr);
    } 
    finally 
    {
        mut.ReleaseMutex();
    }
}
于 2012-04-12T07:15:30.240 回答
0

使用Mutex类:

Mutex mut = new Mutex();
于 2012-04-12T07:17:37.150 回答
0

我认为,如果您不想等待日志(听起来很合乎逻辑),您应该将日志消息推送到同步队列(可从 .net 4 获得)并让后台线程处理所有日志写入。如果您使用互斥锁和锁,它会影响您的性能。在内存队列中写入比文件写入快得多。

于 2012-04-12T07:22:40.127 回答