When I was working on a project some time ago, the system was a multi-threaded program, and several threads needed to write logs. The main thread and communication thread often fought during log writing. To solve this problem, consider locking the log writing method. The Code is as follows:
/// <Summary>
/// Lock when writing logs
/// </Summary>
Private Static object m_lock = new object ();
/// <Summary>
/// Interface function for writing log files. This function only writes strings to specified files.
/// </Summary>
/// <Param name = "destfilename"> </param>
/// <Param name = "FMT"> </param>
/// <Returns> </returns>
Public static int tp_writeapplogfileex (string destfilename, string FMT)
{
String strlogfile = system. environment. currentdirectory + "\ log \" + datetime. Now. tostring ("yyyymmdd") + ". log ";
If (strlogfile! = Destfilename)
{
Destfilename = strlogfile;
}
Int iwriteapplogfile = 0;
Lock (m_lock)
{
Iwriteapplogfile = tp_writeapplogfile (destfilename, FMT );
}
Return iwriteapplogfile;
}
Public static int tp_writeapplogfile (string destfilename, string FMT)
{
Try
{
Fileinfo file = new fileinfo (destfilename );
If (! File. exists)
{
File. Create ();
}
// Locate the end Of the file
Streamwriter stream = file. appendtext ();
// Write the current time
Stream. Write (datetime. Now. tostring ("HH: mm: SS fff "));
// Write the character string passed by the user
Stream. writeline (FMT );
// Remember to close it.
Stream. Close ();
}
Catch (exception E)
{
}
Return 0;
}
After locking, the problem of multi-thread log writing is solved.