Logging

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
 
M

Monkian

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

Ebbe Kristensen

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
 
M

Moshe Peleg

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

im.djmatty

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top