使用Timer用C#5.0 & TPL將讓你調用一個異步事件,其在定義的時間間隔,這將輪詢設備,並自動馬歇爾結果返回到UI線程上。
public partial class Form1 : Form
{
private readonly Timer _sampleTimer;
public Form1()
{
InitializeComponent();
_sampleTimer = new Timer
{
Interval = 500 // 0.5 Seconds
};
_sampleTimer.Tick += SampleUsb;
}
private async void SampleUsb(object sender, EventArgs e)
{
// Since we asynchronously wait, the UI thread is not blocked by "the work".
var result = await SampleUsbDeviceAsync();
// Since we resume on the UI context, we can directly access UI elements.
resultTextField.Text = result;
}
private async Task<string> SampleUsbDeviceAsync()
{
await Task.Delay(1000); // Do actual work sampling usb async (not blocking ui)
return DateTime.Now.Ticks.ToString(); // Sample Result
}
private void startButton_Click(object sender, EventArgs e)
{
_sampleTimer.Start();
}
private void stopButton_Click(object sender, EventArgs e)
{
_sampleTimer.Stop();
}
只要搜索「從後臺線程更新桂」 – 2012-03-22 15:52:47
LB擁有它,你需要一個BackgroundWorker http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx – deltree 2012-03-22 15:53:54
什麼你使用的是GUI框架? WinForms,WPF還是其他? [從後臺線程結果更新的WinForms UI]的 – 2012-03-22 15:54:24