title: Proper way to use DisposeAsync on C# streams
body: <p>I'm writing a method which asynchronously writes separate lines of text to a file. If it's <em>cancelled</em> it deletes the created file and jumps out of the loop.</p>
  <p>This is the simplified code which works fine... And I marked 2 points which I'm not sure how they are being handled. I want the code to not block the thread in any case.</p>
  <pre><code>public async Task&lt;IErrorResult&gt; WriteToFileAsync(string filePath,
                                                   CancellationToken cancellationToken)
  {
      cancellationToken.ThrowIfCancellationRequested();
  
      using var stream = new FileStream(filePath, FileMode.Create);
      using var writer = new StreamWriter(stream, Encoding.UTF8);
  
      foreach (var line in Lines)
      {
          if (cancellationToken.IsCancellationRequested)
          {
              //
              // [1] close, delete and throw if cancelled
              //
              writer.Close();
              stream.Close();
              if (File.Exists(filePath))
                  File.Delete(filePath);
              throw new OperationCanceledException();
          }
  
          // write to the stream
          await writer.WriteLineAsync(line.ToString());
      }
  
      //
      // [2] flush and let them dispose
      //
      await writer.FlushAsync();
      await stream.FlushAsync();
      // await stream.DisposeAsync(); ??????
      return null;
  }
  </code></pre>
  <h2>1</h2>
  <p>I'm calling <code>Close()</code> on <code>FileStream</code> and <code>StreamWriter</code> and I think it will run synchronously and blocks the thread. How can I improve this? I don't want to wait for it to flush the buffer into the file and then delete the file.</p>
  <h2>2</h2>
  <p>I suppose the <code>Dispose</code> method will be called and not <code>DisposeAsync</code> at the end of the <code>using</code> scope. (<em>is this assumption correct?</em>).</p>
  <p>So <code>Dispose</code> blocks the thread and in order to prevent that I'm flushing first with <code>FlushAsync</code> so that <code>Dispose</code> would perform <em>less</em> things. (<em>to what extent is this true?</em>)</p>
  <p>I could also remove <code>using</code> and instead I could write <code>DisposeAsync</code> manually in these two places. But it will decrease readability.</p>
  <p>If I open the <code>FileStream</code> with <code>useAsync = true</code> would it automatically call <code>DisposeAsync</code> when <code>using</code> block ends?</p>
  <hr />
  <p>Any explanation or a variation of the above code which performs better is appreciated.</p>