TPL: check if task was faulted in OnCompleted even

2019-09-24 01:57发布

I have a task like:

var migrateTask = Task.Run(() =>
    {
        //do stuff
     });

migrateTask.ConfigureAwait(true).GetAwaiter().OnCompleted(this.MigrationProcessCompleted);

How to tell in the method MigrationProcessCompleted if I got an exception or task was faulted in the initial thread (in do stuff code block)?

Is there a way to find this without making the task a class member/property?

1条回答
甜甜的少女心
2楼-- · 2019-09-24 02:24

You should never be really calling .GetAwaiter() it is intended for compiler use.

If you can use await your code is as simple as

public async Task YourFunc()
{

    Exception error = null
    try
    {
        await Task.Run(() =>
        {
            //do stuff
         });
    }
    catch(Exception ex)
    {
        error = ex;
    }

    MigrationProcessCompleted(error)
}

private void MigrationProcessCompleted(Exception error)
{
     //Check to see if error == null. If it is no error happend, if not deal withthe error.
}
查看更多
登录 后发表回答