6

It's been a while since I last used XmlWriter but since today has been a lucky day to write some XML, so I started to use all the ...Async methods by default but straight away I get the following exception:

System.InvalidOperationException : Set XmlWriterSettings.Async to true if you want to use Async Methods.

It seems a bit weird to me that I have to set a flag on a settings object that I pass into the constructor of XmlWriter so that I can open up the use of methods on a class.

For example:

using (var xmlWriter = XmlWriter.Create(stringBuilder))
{
    await xmlWriter.WriteStartElementAsync("", "root", "")
        .ConfigureAwait(false);
}

Will throw an exception, however:

using (var xmlWriter = XmlWriter.Create(stringBuilder, new XmlWriterSettings(){Async = true}))
{
    await xmlWriter.WriteStartElementAsync("", "root", "")
        .ConfigureAwait(false);
}

Will work fine.

Does anyone know the reasoning behind this?

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
  • 6
    I could *guess*. If you look at the internals, you'll see that it returns a special [wrapper](https://referencesource.microsoft.com/#System.Xml/System/Xml/Core/XmlAsyncCheckWriter.cs,6b9a7497731f9b46) when `Async` is true, which is making sure that only one activity is happening at a time. I guess deep in the guts there are some non-atomic uses of the `TextWriter` object so it has to protect access to it but they didn't want to incur the checking costs for existing code that wouldn't use any async methods. – Damien_The_Unbeliever Sep 11 '17 at 14:20

0 Answers0