如何在构造函数中捕获异步方法的异常?

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

我有一个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;

click事件会触发异步调用

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()

?

c# winforms
1个回答
4
投票

要处理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:....";
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.