Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#streamwriter调用_C#_Invoke_Streamwriter - Fatal编程技术网

C#streamwriter调用

C#streamwriter调用,c#,invoke,streamwriter,C#,Invoke,Streamwriter,我想在跨线程中访问并写入一个txt文件,但软件会给出一个例外,因为多个线程希望同时访问同一个文件。如何调用streamwriter以避免异常?这是我的密码: void WriteLog(string LogStr) { StreamWriter sw = new StreamWriter("Log.txt", true); sw.WriteLine(LogStr); sw.Close(); } 我在线程中调用WriteLog方法 谢谢。您可以尝试使用互斥锁: priva

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

void WriteLog(string LogStr)
{
    StreamWriter sw = new StreamWriter("Log.txt", true);
    sw.WriteLine(LogStr);
    sw.Close();
}
我在线程中调用WriteLog方法


谢谢。

您可以尝试使用互斥锁:

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();
    }
}

使用
Mutex
类:

Mutex mut = new Mutex();

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

使用NLog或log4net之类的工具是不可能的吗?这将为您解决问题,因为他们可以处理所有这些复杂性。顺便说一句,每次想记录邮件时打开和关闭一个文件都会让您在将来非常头疼。