如何异步读取 XML 文件?

G. *_* LC 3 c# asynchronous xmlreader

我正在编写一个用于数据后处理的 Windows 窗体应用程序。我有一个面板,允许拖放文件。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...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

System.InvalidOperationException:
Set XmlReaderSettings.Async to true if you want to use Async Methods.
Run Code Online (Sandbox Code Playgroud)

发生此错误的原因是我标有FIRST ERROR的那一行。我尝试通过取消注释上面标有SECOND ERROR的行来解决此问题。现在,当我拖放时,出现错误:

System.Xml.Xml.XmlException:
The XmlReaderSettings.Async property is read only and cannot be set
Run Code Online (Sandbox Code Playgroud)

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

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

然后给出了发生第二个错误的原因。但是,我无法让它发挥作用。有小费吗?

ESG*_*ESG 5

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

XmlReaderSettings settings = new XmlReaderSettings 
{
    Async = true   
};
XmlReader reader = XmlReader.Create(filePath, settings);
Run Code Online (Sandbox Code Playgroud)

参考资料: 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