在UI构造函数中使用Task.Run()时处理异常 [英] Handle exception when using Task.Run() in UI constructor

查看:37
本文介绍了在UI构造函数中使用Task.Run()时处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用 Task.Run()的构造函数,如下所示:

I have a constructor that call Task.Run() like this:

public MyPage() {
    Task.Run(() => {
        MyHeavyCpuMethod();
    });
}

在这里, MyPage()是UI组件的构造函数,我不希望 MyHeavyCpuMethod()在我的UI线程上运行,因此我将其卸载了使用 Task.Run()以即发即弃的方式进行,因为我真的不在乎 MyHeavyCpuMethod()何时完成.

Here, MyPage() is the constructor of a UI component, and I don't want MyHeavyCpuMethod() to run on my UI thread, so I offload it with Task.Run() in a fire-and-forget fashion since I don't really care when MyHeavyCpuMethod() finishes.

但是,如果 MyHeavyCpuMethod()抛出,我将无法处理返回的Task中的异常.

However, this way if MyHeavyCpuMethod() throws, I can't handle the exception that is in the returned Task.

在这种情况下如何处理错误?

How can I do error handling in this case?

推荐答案

一个选项是使用async/await ...不适用于构造函数,但可以在静态方法:

One option is to use async/await... which doesn't work with a constructor, but which can work in a static method:

public static async Task<MyPage> CreateInstance()
{
    await Task.Run(...);
    // Anything else asynchronous you want to use
    return new MyPage();
}

然后假设您正在使用 异步方法,则可以使用:

And then assuming you're using this from an async method, you can just use:

MyPage page = await MyPage.CreateInstance();

这样,如果CPU绑定任务失败,您甚至都不会进入构造函数调用.构造函数调用本身在这里应该很快,因为放在UI线程上(如您所愿).

That way, if the CPU-bound task fails, you won't even get to the constructor call. The constructor call itself is expected to be fast here, as that will be on the UI thread (as you want it to be).

对此的一种替代方法,您可以将 Task.Run 返回的任务存储为页面中的字段,然后等待构建后...使用常规的异步异常处理方法

An alternative to this, you could potentially store the task returned by Task.Run as a field in the page, and then await that post-construction... using the normal async exception handling approaches.

这篇关于在UI构造函数中使用Task.Run()时处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆