如何异步读取XML文件?

时间:2018-08-06 01:27:12

标签: c# asynchronous xmlreader

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

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文件时,出现以下错误:

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

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

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

所以我转到XmlReaderSettings.Async属性的MS Docs,它说:

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

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

1 个答案:

答案 0 :(得分:2)

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

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

相关问题