title: Writing to file in a thread safe manner
body: <p>Writing <code>Stringbuilder</code> to file asynchronously. This code takes control of a file, writes a stream to it and releases it. It deals with requests from asynchronous operations, which may come in at any time.</p>
  
  <p>The <code>FilePath</code> is set per class instance (so the lock <code>Object</code> is per instance), but there is potential for conflict since these classes may share <code>FilePaths</code>. That sort of conflict, as well as all other types from outside the class instance, would be dealt with retries.</p>
  
  <p>Is this code suitable for its purpose? Is there a better way to handle this that means less (or no) reliance on the catch and retry mechanic? </p>
  
  <p>Also how do I avoid catching exceptions that have occurred for other reasons.</p>
  
  <pre><code>public string Filepath { get; set; }
  private Object locker = new Object();
  
  public async Task WriteToFile(StringBuilder text)
      {
          int timeOut = 100;
          Stopwatch stopwatch = new Stopwatch();
          stopwatch.Start();
          while (true)
          {
              try
              {
                  //Wait for resource to be free
                  lock (locker)
                  {
                      using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                      using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                      {
                          writer.Write(text.ToString());
                      }
                  }
                  break;
              }
              catch
              {
                  //File not available, conflict with other class instances or application
              }
              if (stopwatch.ElapsedMilliseconds &gt; timeOut)
              {
                  //Give up.
                  break;
              }
              //Wait and Retry
              await Task.Delay(5);
          }
          stopwatch.Stop();
      }
  </code></pre>