3

我创建了一个小型 C# 应用程序,它应该异步地从 XML 文件中提取所有值。问题是..它不是异步的,我看不出哪里出错了。单击按钮时,UI 冻结,应用程序无法移动等,显示出它同步运行的所有迹象。

谁能明白为什么会这样?

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;
            }
        }
    }
}
4

2 回答 2

4

调用SearchFiles(string path)一个Task. 如下。

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";
}

我建议你阅读这篇文章async关键字await

于 2013-09-25T12:35:28.710 回答
3

我猜这个问题是由于XmlDocument.Load同步加载的。

尝试使用XmlReader从异步文件流创建的。

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;
        }
    }
}
于 2013-09-25T12:45:02.417 回答