首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何异步读取XML文件?

如何异步读取XML文件?
EN

Stack Overflow用户
提问于 2018-08-06 01:27:12
回答 1查看 4K关注 0票数 3

我正在为数据后处理编写一个Windows表单应用程序.我有一个面板,我允许文件被拖放。XML文件将相当大(足以减缓UI的速度)。因此,我想异步读取该文件。到目前为止,对于应用程序的这一部分,我有两种方法:

代码语言:javascript
复制
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文件时,会得到以下错误:

代码语言:javascript
复制
System.InvalidOperationException:
Set XmlReaderSettings.Async to true if you want to use Async Methods.

发生此错误是因为我使用FIRST ERROR标记的行。我试图通过取消上面的行注释来解决这个问题,我用第二个错误标记了该行。现在,当我拖放时,我得到了错误:

代码语言:javascript
复制
System.Xml.Xml.XmlException:
The XmlReaderSettings.Async property is read only and cannot be set

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

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

然后给出了第二个错误发生的原因。但是,我不能让这件事起作用。有小费吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 02:06:06

您需要使用适当的设置创建XmlReader。

代码语言:javascript
复制
XmlReaderSettings settings = new XmlReaderSettings 
{
    Async = true   
};
XmlReader reader = XmlReader.Create(filePath, settings);

参考资料:https://msdn.microsoft.com/en-us/library/ms162474(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings(v=vs.110).aspx

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51699544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档