我有一个 Winforms 程序,以下是构造函数,它创建一个计时器来限制昂贵的异步调用。
public partial class Form1: Form
{
public Form1()
{
_timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
_timer.Tick += (s, e) =>
{
_flag = false;
_timer.Stop();
try
{
Task.Run(async () => await Presenter.Search()); // Call async DB calls
}
catch (Exception ex) // Cannot capture the Exception of `Presenter.Search()`
{
MessageLabel.Text = "Error:....";
}
};
}
private readonly DispatcherTimer _timer;
private bool _flag;
并且点击事件触发异步调用
public void OnCheckedChanged(object sender, EventArgs e)
{
if (!_flag)
{
_flag = true;
_timer.Start();
}
}
如何捕获异常Presenter.Search()
并在表单中显示错误?
如果我改变它会阻塞UI线程吗
Task.Run(async () => await Presenter.Search());
至
Presenter.Search().RunSynchronously()
?
要处理异常表单,Presenter.Search
只需为您的Tick
事件使用异步事件处理程序。
_timer.Tick += async (s, e) =>
{
_flag = false;
_timer.Stop();
try
{
await Presenter.Search(); // Call async DB calls
}
catch (Exception ex) // Cannot capture the Exception of `Presenter.Search()`
{
MessageLabel.Text = "Error:....";
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句