简体   繁体   中英

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. The 3rd party Dll creates multiple threads so it can trigger events within each thread.

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. Otherwise take a look at something like log4net, they have solutions for logging to files from multiple threads.

It could happen. I would use the FileStream class to use log files. It tries to get access to the file by opening it.

if the FileStream class raises and exception the file is being used

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. 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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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