I have a static function that write to a log file .
In my project I am already using multithreading ,
hense I m getting exception that
'process can't access file because it is being used by another process '

I want to mutex that code so that if one thread is accessing that code then another will have to wait.
Here is the code.

{
                private static Mutex mut = new Mutex();
                mut.WaitOne();
                StreamWriter sw = new StreamWriter(path + "\\" + logFileName, true);
                sw.WriteLine(stMessage);
                sw.Close();
                mut.ReleaseMutex();

            }

sorry to say that 'lock' keyword is not synchronizing file write process.

Here is code
StreamWriter sw;
lock( sw )
{
sw=new StreamWriter( FileNameAlongWithPath , true );
sw.WriteLine("Xyz");
sw.Close();
}


but again exception comes that
'process can't access file because it is being used by another process '


Can u suggest me another way to synchronize the code so that other threads will have to wait untill specified code is not get executed.

You said that you're already using multi-threading on your project. It seems that you're actually going to a race condition somewhere on your code. Check it out.

To solve your problem in writing to a log file with multiple threads, a good way to do it is to queue up your messages going to your logger. Let that logger dequeue your messages alone so that you wont encounter any problems with it. You will only synchronize your code on queueing and dequeuing your messages.

Yes,You are right, there is possibility of race condition due to multithreading and if I enqued all messages to write to the file;
imagine what will happen if my program crashes at a point before writing all messages ? I want to log each and every activity done by my program.
Don't you think it is more harmful way than the way am using now?

Yes, you'll sacrifice everything just to write on your log file which is not a good idea. Looking at a big picture lets say you just have 2 threads on your project. Each thread has a long task to do and they need to lock your writer. Your threads will not function correctly and wait for the other just to write on your logs than to do its main purpose.

I suggest that you look into the code of Patterns and Practices enterprise Library. This is an opensource library supported by Microsoft. You can even download it for free. This library has its on logging module that will solve your problem.

If you have enough time you can look on the codes and study it for future reference.

By the way check out how they synchronized their queue. You have a good grasp of how should locking be done.

See http://entlib.codeplex.com/Wikipage

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.