Using a lock in the second example will not work properly, because you create a new lock object and lock it every time.
What you really need, a wise file looks something like this:
public static void WriteLog(string source, string message) { string logFilePath = @"C:\LogFile\log.txt"; using (FileStream file = new FileStream(logFilePath,FileMode.Append,FileAccess.Write,FileShare.None)) { StreamWriter writer = new StreamWriter(file); writer.write(source + ": : " + message); file.Flush(); file.Close(); } }
This should be solely locking the file during recording, but properly closing the file after execution.
This does NOT solve the problem of streaming because two streams can still collide. If one thread locks the file, subsequent requests will not be executed.
To solve this problem with blocking, move the blocking object to statics, which all threads can share and block, for example:
public static class Logger { private static object locker = new object(); public static void Log(string source, string message) { lock (locker) { string logFilePath = @"C:\LogFile\log.txt"; using (FileStream file = new FileStream(logFilePath,FileMode.Append,FileAccess.Write,FileShare.None)) { StreamWriter writer = new StreamWriter(file); writer.write(source + ": : " + message); writer.Flush(); file.Close(); } } } }
This will cause subsequent threads to wait until the lock is available before writing to the file, as expected.
Note. Oded remark, although this applies to this method.
Lloyd source share