Wednesday, March 13, 2013

Solution for the error in a multi threaded environment. Error: The process cannot access the file 'D:\[File].log' because it is being used by another process

In a multi threaded environment if you call a below WriteLog() function you will get the below error:
Error: "The process cannot access the file 'D:\Error.log' because it is being used by another process."
            public void WriteLog(string msg)
            {
                using (StreamWriter sw = File.AppendText("D:\\Error.log"))
                {
                    sw.Write(msg);
                    sw.Close();
                }
            }

To resolve this issue, It is recommended to lock on a separate simple object. This reduces the risk of anything else locking on the same object. Below is the example:
            static readonly object writerLock = new object();
            public void WriteLog(string msg)
            {
                lock (writerLock)
                {
                    using (StreamWriter sw = File.AppendText("D:\\Error.log"))
                    {
                        sw.Write(msg);
                        sw.Close();
                    }
                }
            }

No comments:

Post a Comment