Logging

  • Thread starter Thread starter Moshe Peleg
  • Start date Start date
M

Moshe Peleg

Hi,

I'm developing a multiple threads application.
I need to log several events in the different threads into the same text
file.
The add_2_log function is very simle:

using (StreamWriter sw = new StreamWriter(log_file_name,true))
{

sw.Write (DateTime.Now.Date.Day.ToString().PadLeft(2, '0') +"/" +
DateTime.Now.Date.Month.ToString().PadLeft(2, '0') + "/" +
DateTime.Now.Date.Year.ToString() + "," + DateTime.Now.TimeOfDay.ToString()
+ "," + message + "," + code1.ToString() + "," + code2.ToString());

}



Do I need to add a Mutex in order to prevent thread trying to add a line
while file is already open for current ?



Thanks,



MP
 
Using lock(obj) in C# would be preferred as this compiles to

Monitor.Enter(obj)
try
{
//work
}
finally
{
Monitor.Exit(obj);
}

Monitor exposes locking mechanics supported by the CLR.

Using a Mutex in managed code simply provides a managed wrapper around a
kernal object and as such is the more heavyweight solution. Mutexes should
really only be used where inter-process synchronisation is required.
 
Moshe said:
Do I need to add a Mutex in order to prevent thread trying to add a
line while file is already open for current ?

Yes - but keep in mind that if one thread blocks another because of logging,
the flow of execution in your application has changed from what it would be
without logging.

Ebbe
 
Thank you very much.

Does the same answer goes for timers ?
Is it the same for the "ordinary" control timers ?
I understand they are on the same thread, but the do interrupt the main
program.
Therefore they also might cause the same problem.
 
Yeah, how about having the threads submit log messages to a queue, and
have another thread reading from the queue and writing the log
messages to a file?

Matt
 
Back
Top