异步数据读取

问题描述 投票:0回答:1

我目前正在WinForm C#中开发一个应用程序,以周期性地显示设备中的值。这是一个简短的示例:

public partial class MainForn : Form
{
    private System.Windows.Forms.Timer timer1;

    public MainForn()
    {
        InitializeComponent();
        timer1 = new System.Windows.Forms.Timer(this.components);
        timer1.Enabled = true;
        timer1.Tick += new System.EventHandler(this.timer1_Tick);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        ReadDeviceData();
        label1.Text = Convert.ToString(ReadDeviceData());
    }

    private int ReadDeviceData()
    {
        Thread.Sleep(300);//Simulation of long treatment for reading
        Random rnd = new Random();
        return rnd.Next();            
    }

}

在此示例中,UI在300ms的ReadDeviceData()期间冻结。知道此方法将无休止地执行,使ReadDeviceData()异步的最佳方法是什么?

谢谢。

c# .net winforms
1个回答
2
投票

这应该可以解决问题:

//random is seeded based on current time; so best to do it once
Random rnd = new Random();

//the has the extra async keyword
private async void timer1_Tick(object sender, EventArgs e)
{
    //await this call because you need its data
    var data = await ReadDeviceData();
    //set the data; note: use the variable here
    label1.Text = Convert.ToString(data);
}

//signature changed
private async Task<int> ReadDeviceData()
{
    //await a Task.Delay. (Thread.Sleep is thread blocking)
    await Task.Delay(300);//Simulation of long treatment for reading        
    return rnd.Next();            
}

因此,这是借助您的模拟进行的。如果您实际上是在联系硬件;希望它有一个API,其中包含一些基于任务的方法。如果是这样的话;如果不是这样,它很容易:您需要自己进行转换,这很棘手。

在这种情况下,我们需要有关设备API的更多信息。

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