title: FileOptions.Asynchronous causes FileStream.BeginRead to block
body: <p>Why does creating a FileStream with FileOptions.Asynchronous cause FileStream.BeginRead to block the calling thread?</p>
  
  <p>Here is the code snippet:</p>
  
  <pre><code>private static Task&lt;int&gt; ReadFileAsync(string filePath)
    {
       var file = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 64 * 1024, FileOptions.Asynchronous);
       FileInfo fi = new FileInfo(filePath);
       byte[] buffer = new byte[fi.Length];
       Task&lt;int&gt; task = Task&lt;int&gt;.Factory.FromAsync(file.BeginRead, file.EndRead, buffer, 0, buffer.Length, null);         
       return task.ContinueWith(t =&gt;
       {
          file.Close();
          Console.WriteLine("Done ReadFileAsync, read " + t.Result + " bytes.");
          return t.Result;
       });
    }
  </code></pre>
  
  <p>When digging around in the MSFT FileStream code using JetBrains dotPeek it seems like there is a bug in their code:</p>
  
  <pre><code>      if (!this._isAsync)
      return base.BeginRead(array, offset, numBytes, userCallback, stateObject);
    else
      return (IAsyncResult) this.BeginReadAsync(array, offset, numBytes, userCallback, stateObject);
  </code></pre>
  
  <p>The BeginRead method actually seems to do reading asynchronously by scheduling a Task, but the BeginReadAsync method actually ends up doing a synchronous read.
  So their method naming nomenclature is backwards and the logic of which method is called is wrong. BeginRead should be called if this._isAsync == true.</p>
  
  <p>So it seems that to get FileStream.BeginRead to return right away (asynchronously schedule a read) you actually have to set the useAsync parameter in the cosntructor to false.</p>