title: Will lock prevent the error "The process cannot access the file because it is being used by another process"?
body: <p>Here is my log writing function:</p>
  
  <pre><code>public static void WriteLog(string source, string message)
  {
      string logFilePath = @"C:\LogFile\log.txt";
      using (StreamWriter sw = new StreamWriter(logFilePath, true))
      {
          sw.Write(source + ": :" + message);
      }
  }
  </code></pre>
  
  <p>But this code sometimes caused me the error:</p>
  
  <blockquote>
    <p>The process cannot access the file because it is being used by another process</p>
  </blockquote>
  
  <p>So I modified my code a bit, and here is my new code:</p>
  
  <pre><code>public static void WriteLog(string source, string message)
  {
      object _lock = new object();
      lock (_lock)
      {
          string logFilePath = @"C:\LogFile\log.txt";
          using (StreamWriter sw = new StreamWriter(logFilePath, true))
          {
              sw.Write(source + ": :" + message);
          }
      }
  }
  </code></pre>
  
  <p>Though I haven't received an error after using this code. But still I just wanted to know if this is correct way to use lock to prevent such errors due to deadlock, and if the way I have used lock is correct or not.</p>