如何异步读取XML文件? [英] How to read in an XML file asynchronously?

查看:66
本文介绍了如何异步读取XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Windows Form应用程序以进行数据后处理.我有一个面板,可以在其中拖放文件.XML文件将很大(足以使UI变慢).因此,我想异步读取文件.到目前为止,对于应用程序的这一部分,我有两种方法:

I am writing a Windows Form Application for data post-processing. I have a panel where I allow for files to be dragged and dropped. The XML files will be quite large (enough to slow the UI down). Therefore I would like to read the file in asynchronously. So far for this part of the app I have two methods:

namespace myApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void DragDropPanel_DragEnter(object sender, DragEventArgs e)
        {
            // Trigger the Drag Drop Event
            e.Effect = DragDropEffects.Copy;
        }

        private async void DragDropPanel_DragDrop(object sender, DarEventArgs e)
        {
            // Identifiers used are:
            string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
            string filePath = filePaths[0],
                 fileName = System.IO.Path.GetFileName(filePath);

             // Read in the file asynchronously
             XmlReader reader = XmlReader.Create(filePath);
             //reader.Settings.Async = true; // ** (SECOND ERROR) ** \\
             while (await reader.ReadAsync()) // ** (FIRST ERROR) ** \\
             { 
                  Console.WriteLine("testing...");
             }

             // Do other things...
        }
    }
}

现在,当我拖放XML文件时,出现以下错误:

Now when I drag and drop the XML file I get the following error:

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

由于我标有 FIRST ERROR (第一错误)的行而发生此错误.我试图通过取消注释上面用第二错误标记的行来对其进行注释来解决此问题.现在,当我拖放时会收到错误消息:

this error occurs because of the line I labeled with FIRST ERROR. I attempt to fix this by uncommenting the line above it which I have labeled with SECOND ERROR. Now when I drag and drop I get the error:

System.Xml.Xml.XmlException:
The XmlReaderSettings.Async property is read only and cannot be set

因此,我转到 XmlReaderSettings.Async 属性,它说:

So I go to the MS Docs for the XmlReaderSettings.Async property and it says:

如果要在该实例上使用异步XmlReader方法,则必须在创建新的XmlReader实例时将此值设置为true .

然后说明第二次错误发生的原因.但是,我无法使它正常工作.有提示吗?

Which then gives the reason why the SECOND ERROR occurs. However, I cannot get this to work. Any tips?

推荐答案

您需要使用正确的设置创建XmlReader.

You need to Create the XmlReader with the proper settings.

XmlReaderSettings settings = new XmlReaderSettings 
{
    Async = true   
};
XmlReader reader = XmlReader.Create(filePath, settings);

参考: https://msdn.microsoft.com/zh-我们/图书馆/ms162474(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings(v = vs.110).aspx

这篇关于如何异步读取XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆