Search code examples
c#streamwriter

Write in a txt file from two threads


I am using a routine for catching any exception inside my project. Then i am write it inside a text file. But how can i prevent an exception if i will try to write into the txt file from two different threads?

public static void LogFile(string ex)
    {
        try
        {
            string strPath = @"C:\Log.txt";
            if (!File.Exists(strPath))
                File.Create(strPath).Dispose();

            using (StreamWriter sw = File.AppendText(strPath))
            {
                // sw.WriteLine("=============Error Logging ===========");
                sw.WriteLine("===========Start============= " + DateTime.Now);
                sw.WriteLine("Error Message: " + ex);
                //sw.WriteLine("Stack Trace: " + ex.StackTrace);
                sw.WriteLine("===========End============= " + DateTime.Now);
                sw.WriteLine();

            }
        }
        catch
        {

        }
    }

When two threads at the same time are trying to write in my LogFile.txet then i am getting exception that *txt file is been in used.


Solution

  • you need to make your bloc syncronzed for example like the code below. There are more examples here: C# version of java's synchronized keyword?

    On a side note, there are things that are not considered good practices like ignoring the exception. You might consider also using a logging library which can take care about multi-threading, performance and such...

    static object Lock = new object();
    
    
    
    
    public static void LogFile(string ex)
        {
    lock (Lock) {
            try
            {
                string strPath = @"C:\Log.txt";
                if (!File.Exists(strPath))
                    File.Create(strPath).Dispose();
    
                using (StreamWriter sw = File.AppendText(strPath))
                {
                    // sw.WriteLine("=============Error Logging ===========");
                    sw.WriteLine("===========Start============= " + DateTime.Now);
                    sw.WriteLine("Error Message: " + ex);
                    //sw.WriteLine("Stack Trace: " + ex.StackTrace);
                    sw.WriteLine("===========End============= " + DateTime.Now);
                    sw.WriteLine();
    
                }
            }
            catch
            {
    
            }
        }
    }