Good day.

I have a situation where 2 threads are trying to write their own logs to the file.

Logging procedure:

private object threadLock = new object(); ... private void AddTextToFile(string log) { lock (threadLock) { StreamWriter _testData = null; try { _testData = new StreamWriter(_path, true, System.Text.ASCIIEncoding.Unicode); _testData.WriteLine(String.Format("[{0}] {1}", DateTime.Now, log)); _testData.Flush(); } finally { if (_testData != null) { _testData.Close(); // Close the instance of StreamWriter. _testData.Dispose(); // Dispose from memory. } } } } 

The blocking token is, how to avoid this error? Error text:

C: \ Logs \ SmsGate \ SmsInspector.txt, because it is being used by another process.

In theory, it should not be. What am I doing wrong? Thank.

  • the class in which all this is declared is singleton? threadLock you accidentally should not be static? - PashaPash

1 answer 1

The problem is not in this code. Your code is written correctly. You do not close the file somewhere else. Or another thread uses another threadLock .


PS: Why is it so difficult, you can simply

 lock (threadLock) { File.AppendAllText( _path, string.Format("[{0}] {1}", DateTime.Now, log), Encoding.Unicode); }