Question

I have created a small C# application that should pull all values from an XML file asynchronously. The problem is.. it's not asynchronous and I can't see where I'm going wrong. When the button is clicked the UI freezes, the application can't be moved etc, showing all the signs of it running synchronously.

Can anyone see why this is happening?

private async void parseAndExportBtn_Click(object sender, EventArgs e)
{
    progressBar1.MarqueeAnimationSpeed = 100;
    parseAndExportBtn.Enabled = false;
    selectDirectoryBtn.Enabled = false;
    status.Text = "Started searching files...";
    await SearchFiles(selectTxcDirectory.SelectedPath);
    status.Text = "Finished searching files";
}

private static async Task SearchFiles(string path)
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(path + "/cen_18-2_-1-y11.xml");

    using (XmlReader r = XmlReader.Create(new StringReader(xmlDoc.InnerXml), new XmlReaderSettings() { Async = true }))
    {
        while (await r.ReadAsync())
        {
            switch (r.NodeType)
            {
                case XmlNodeType.Text:
                    Console.WriteLine(await r.GetValueAsync());
                    break;
            }
        }
    }
}
Was it helpful?

Solution

Call SearchFiles(string path) in a Task. As below.

private void parseAndExportBtn_Click(object sender, EventArgs e)
{
    progressBar1.MarqueeAnimationSpeed = 100;
    parseAndExportBtn.Enabled = false;
    selectDirectoryBtn.Enabled = false;
    status.Text = "Started searching files...";

    Task t = Task.Run(() => SearchFiles(selectTxcDirectory.SelectedPath));

    status.Text = "Finished searching files";
}

I suggest you read this article on async and await keywords.

OTHER TIPS

I'm guessing that the problem is due to XmlDocument.Load, which loads synchronously.

Try using an XmlReader that is created from an asynchronous file stream.

using (var file = new FileStream(path + "/cen_18-2_-1-y11.xml", FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
using (XmlReader r = XmlReader.Create(file, new XmlReaderSettings() { Async = true }))
{
    while (await r.ReadAsync())
    {
        switch (r.NodeType)
        {
            case XmlNodeType.Text:
                Console.WriteLine(await r.GetValueAsync());
                break;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top