在C#中连续读取XML

问题描述 投票:-1回答:2

我有XML文件如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<sami>
<title>IN[1]=false</title>
<title>IN[2]=true</title>
<title>OUT[1]=true</title>
<title>OUT[2]=flase</title>
<title>OUT[3]=flase</title>
<title>OUT[4]=flase</title>
<title>$IN[5]=false</title>
</sami>

问题:如何使用C#每秒读取xml数据?

我尝试了以下方法:

private void Form1_Load(object sender, EventArgs e)
{
    DateTime nextRead;
    Thread thread = new Thread(() =>
    {
        nextRead = DateTime.Now.AddSeconds(1000);
        XDocument doc = XDocument.Load("C:\\Users\\lenovo\\Desktop\\Sxml.xml");
        var result = doc.Descendants("title").ToList();
        textBox1.Text = result[0].Value;
      //  listBox1.Items.Add(result[0].Value);
       // listBox1.Items.Add(result[1].Value);
       // listBox1.Items.Add(result[2].Value);
        Thread.Sleep(Math.Max(0, (DateTime.Now - nextRead).Milliseconds));

    });
    thread.Start();
}
c# xml xml-parsing readxml
2个回答
1
投票

您可以使用Task.Delay重复读取xml文件。 1,创建一个重复读取xml文件的任务方法:

static async Task RepeadtReadingXml(int delayMillis, int repeatMillis, CancellationToken ct)

    {

        Console.WriteLine("{0}: Start reading xml file", DateTime.Now);

        await Task.Delay(delayMillis, ct);

        while (true)

        {

            Console.WriteLine("{0}: Reading xml file every 1 sec", DateTime.Now);

            //***************************************************//
            //     Add you logic to read your xml file here      //
            //***************************************************//

            await Task.Delay(repeatMillis, ct);

        }

    }

并将其称为您需要重复阅读的地方:

            var cts = new CancellationTokenSource(); // Work for 5 sec  

            try

            {

                RepeadtReadingXml(2000, 1000, cts.Token).Wait();

            }

            catch (AggregateException ae)

            {

                ae.Handle(e => e is TaskCanceledException);

            }

0
投票

为此,您需要从工具箱添加到表单Timer

将qazxsw poi间隔设置为1000毫秒。为qazxsw poi事件创建事件处理程序:

timer1
© www.soinside.com 2019 - 2024. All rights reserved.