简体   繁体   English

C#在第3方dll创建的事件中记录到文件。 这会导致锁定吗?

[英]C# Logging to a file in events created by 3rd party dll. Can this cause locking?

I'm logging to a text file with the below. 我正在使用以下内容登录到文本文件。 Log() is being called from within events in my code which are triggered by a 3rd party Dll. 从我的代码中的事件中调用了Log(),这些事件是由第三方Dll触发的。 The 3rd party Dll creates multiple threads so it can trigger events within each thread. 第三方Dll创建多个线程,因此它可以触发每个线程内的事件。

My question is when events are triggered within my code to perform the below logging am i potentially raising an issue where there are two events are trying to write to the log file at the same time and Locking or do events occur one at a time? 我的问题是,何时在我的代码中触发事件以执行以下日志记录,是否可能会引发一个问题,即有两个事件试图同时写入日志文件,并且一次锁定还是一次发生事件?

private void Log(string message)
{
        if(!Directory.Exists(AssemblyDirectory + @"\Logs"))
            Directory.CreateDirectory(AssemblyDirectory + @"\Logs");

        using (StreamWriter sw = new StreamWriter(AssemblyDirectory + @"\Logs\" + DateTime.Today.ToString("yyyyMMdd") + ".log", true))
        {
            sw.AutoFlush = true;
            sw.Write(message);
        }
}

Yes this can cause concurrency problems, I'm not sure but if you keep 1 StreamWriter open (and preferably a 'lock' statement in your method) it might solve the problem. 是的,这可能会导致并发问题,我不确定,但是如果您打开1个StreamWriter(最好在您的方法中使用“ lock”语句),则可能会解决问题。 Otherwise take a look at something like log4net, they have solutions for logging to files from multiple threads. 否则,请看一下log4net之类的东西,它们提供了用于从多个线程记录文件的解决方案。

It could happen. 可能会发生。 I would use the FileStream class to use log files. 我将使用FileStream类来使用日志文件。 It tries to get access to the file by opening it. 它试图通过打开文件来访问该文件。

if the FileStream class raises and exception the file is being used 如果FileStream类引发并且异常正在使用该文件

System.IO.FileStream fl = new FileStream("path", FileMode.Open);
fl.Write(byte[],int,int);
fl.dispose;

Yes, this can cause problems. 是的,这可能会引起问题。 As Zidad log4net can handle multiple threads. 由于Zidad log4net可以处理多个线程。 On the other hand if you want to keep the logger you've written I suggest you take advantage of the thread's unique id : 另一方面,如果您想保留自己编写的记录器,建议您利用线程的唯一ID

using (StreamWriter sw = new StreamWriter(AssemblyDirectory + @"\Logs\" +
      DateTime.Today.ToString("yyyyMMdd") + 
      (new System.Diagnostics.TraceEventCache()).ThreadId +".log", true))
{
    sw.AutoFlush = true;
    sw.Write(message);
}

After all threads are finished you can construct a single file from the others. 所有线程完成后,您可以从其他线程构造一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM