-1

我有如下 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();
}
4

2 回答 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);

            }
于 2018-09-02T09:53:40.190 回答
0

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

timer1时间间隔设置为 1000 毫秒。为事件创建事件处理程序 timer1.Tick

public partial class Form1 : Form
{
    XDocument doc;

    public Form1()
    {
        InitializeComponent();

        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        doc = XDocument.Load("C:\\Users\\Mi\\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);
    }
}
于 2018-09-02T17:13:46.377 回答