I have multithreaded operation running, each one append some info to my log file. The problem is, sometimes log file is locked for editing and at the same time is accessed by other thread, which throws an exception. How can i make sure the log is properly written?
here are the snippet
try
{
File.AppendAllText(fileName, appendString);
}
catch (System.Exception )
{
}
for now, i just ignore the exception. this cause some of the logs are not written.
You need to synchronize your log writes.
What happens is that two threads are appending to the log file at the same time.
Try the following:
Then, when writing the log:
What this does is the following. You create an object (
Program.LogWriteLock) which you use to “synchronize” your log operations on. Then, when one thread is writing to the log file, the next thread will simply wait on the first thread to complete, and write after that.You can even wrap this into a nice little helper class and you get something like this:
Replace
"log.txt"with your actual log file location.