0

I am currently writing an XML Tree (XElement) to a file synchronously using XmlWriter, specifically via XElement.WriteTo(XmlWriter) on the root element. I'm trying to make that asynchronous (with an await). XmlWriter can be made asynchronous (XmlWriterSettings.Async = true), and has an async version for many of its methods. However, it doesn't have methods to write an XElement (async or not), and there is no async version of XElement.WriteTo(XmlWriter).

What API can be used to write an XElement to a file asynchronously?

dbc
  • 104,963
  • 20
  • 228
  • 340
Jimmy
  • 5,131
  • 9
  • 55
  • 81
  • I really doubt there is a benefit to doing a cpu bound bit of work like that in an async fashion. `Task.Run()` is an option but I think it would be more detrimental to performance than beneficial unless the value was a truly huge amount of data. – Crowcoder Jan 20 '18 at 00:51
  • Thanks for the comment; however, If it was such a bad idea, why does XmlWriter have so many async methods (I'm still perplexed as to why there are none to write XElement)? – Jimmy Jan 20 '18 at 04:04

1 Answers1

1

XmlWriter has a method XmlWriter.WriteNodeAsync(XmlReader, Boolean) to which you can pass the XmlReader returned by XNode.CreateReader() e.g. like so:

public static class XElementExtensions
{
    public static async Task WriteToAsync(this XContainer element, Stream stream, bool defAttr = true, bool indent = false)
    {
        var settings = new XmlWriterSettings
        {
            Async = true,
            CloseOutput = false,
            Indent = indent,
        };          

        using (var writer = XmlWriter.Create(stream, settings))
        using (var reader = element.CreateReader())
        {
            await writer.WriteNodeAsync(reader, defAttr);
        }
    }
}

Then if you have some Stream stream you could write to it as follows:

await element.WriteToAsync(stream, false, true);

Sample .Net fiddle.

dbc
  • 104,963
  • 20
  • 228
  • 340