我曾尝试使用以下代码每 30 秒检查一次来自服务器的报告,但在 30 秒后,应用程序挂起了几秒钟。如何避免挂起问题。 下面的代码我试过了,想在这方面做出什么改变?
System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
dispatcherTimer2.Interval = new TimeSpan(0, 0, 30);
Public void dispatcherTimer2_Tick(object sender, EventArgs e)
{
dispatcherTimer2.start();
//code for function call autoreport();
}
请您参考如下方法:
DispatcherTimer 回调在主 UI 线程上执行并阻止它。 使用 System.Threading.Timer,如果您需要从计时器回调更新用户界面,请使用以下方法之一 调度程序调用 过载。 在代码中是这样的
public partial class MainWindow : Window
{
System.Threading.Timer timer;
public MainWindow()
{
InitializeComponent();
timer = new System.Threading.Timer(OnCallBack, null, 0, 30 * 1000);
}
private void OnCallBack(object state)
{
//code to check report
Dispatcher.Invoke(() =>
{
//code to update ui
this.Label.Content = string.Format("Fired at {0}", DateTime.Now);
});
}
}
