我在应用程序中使用后台工作程序从硬件获取数据并在UI中不断更新。我需要配置硬件以从中获取信息。这里我的要求是每2秒更改一次硬件配置,并需要在UI中更新相应的信息。如何通过适当的同步实现这一目标?
编辑: 我在这里发布我的逻辑:
worker3.WorkerReportsProgress = true;
worker3.WorkerSupportsCancellation = true;
worker3.DoWork += new DoWorkEventHandler(worker3_DoWork);
worker3.ProgressChanged += new ProgressChangedEventHandler(worker3_ProcessChanged);
DispatcherTimer timer = new DispatcherTimer();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += timer_tick;
timer.Start();
worker3.RunWorkerAsync();
}
private void worker3_DoWork(object sender, DoWorkEventArgs e)
{
// Here running infinite loop. In that loop
// i am calling the function in dll which will get the data from harware. Passing info which i got to process changed event
}
private void worker3_ProcessChanged(object sender, ProgressChangedEventArgs e)
{
// Here updating the UI with the information which i got from hardware.
}
private void time_tick(object sender, EventArgs )
{
if(worker3.IsBusy==true)
worker3.CancelAsync();
// Configuring hardware with new options.
// Again start the Background worker
if(worker3.IsBusy!=true)
worker3.RunAsync();
}