Exclude processing when using Task.Run () in the user interface constructor

I have a constructor that calls Task.Run()as follows:

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

Here MyPage()is the constructor of the UI component, and I don’t want it to MyHeavyCpuMethod()run in my user interface thread, so I unload it using Task.Run()fire-and-forget mode, since I don’t care when it finishes MyHeavyCpuMethod().

However, in this way, if it MyHeavyCpuMethod()throws, I cannot handle the exception that is in the returned Task.

How can I do error handling in this case?

+2
source share
2 answers

- async/await... , :

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

, , async, :

MyPage page = await MyPage.CreateInstance();

, , , , . , , ( ).

, Task.Run , , -... .

+3

ContinueWith, , Task ( ):

Task.Run(() => MyHeavyCpuMethod())
    .ContinueWith(task => { /* some action */  }, TaskContinuationOptions.OnlyOnFaulted);

, :

, , .

, :

Task.Run(() =>
{
      throw new Exception();
}).ContinueWith(t =>
{
    Invoke((MethodInvoker)(() => MessageBox.Show("ERROR")));
}, TaskContinuationOptions.OnlyOnFaulted);
0

All Articles