Search code examples
c#filestreamxelementasync-awaitc#-5.0

XElement to file save with async/await in C#


I tried to write xml file from XElement object with async/await feature. But I realized the XElement.Save() does not operate with async/await.

Maybe the solution can be to use XElement.Save(Stream) with FileStream object...

So, I write some code as below but hard to treat with filestream things.

public async Task SaveAsync(XElement xml, string filename)
{
    using (var fs = new FileStream(filename, FileMode.Create))
    {
        xml.Save(fs);
        await fs.WriteAsync(**please_help_me**);
    }
}

how to do with this approach or is there any other solution?


Solution

  • XElement does not have any methods to write itself asynchronously, so any calls you make with it will be synchronous. If you need to make this method asynchronous (for example, this happens in the UI thread, and you want to do it on the background thread so that the application doesn't appear to "freeze" while the XML is being saved), you may want to start a new task, and save it on the background.

    public async Task SaveAsync(XElement xml, string filename)
    {
        await Task.Factory.StartNew(delegate
        {
            using (var fs = new FileStream("myFile", FileMode.Create))
            {
                xml.Save(fs);
            }
        });
    }