Search code examples
c#streamappenddisposeusing

Write large data with WriteLineAsync in a using block


Can the following code cause an error, if WriteLineAsync is not finished with writing, but the using term tries to dispose the writer stream?

For example:

using (var writer = System.IO.File.AppendText(fileName))
{ 
    writer.WriteLineAsync(message);
}

What does happen, if i write very large data, which may takes a few seconds?

Thank you


Solution

  • Yes, stream will be disposed of before the task has completed.

    You should either await the task returned by WriteLineAsync or write to the file synchronously instead, using WriteLine.