How to read in an XML file asynchronously?

女生的网名这么多〃 提交于 2019-12-12 21:03:34

问题


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...
        }
    }
}

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.

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

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

You must set this value to true when you create a new XmlReader instance if you want to use asynchronous XmlReader methods on that instance.

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


回答1:


You need to Create the XmlReader with the proper settings.

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

References: 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



来源:https://stackoverflow.com/questions/51699544/how-to-read-in-an-xml-file-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!