TPL: check if task was faulted in OnCompleted event

*爱你&永不变心* 提交于 2019-12-14 03:35:16

问题


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:


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.
}


来源:https://stackoverflow.com/questions/40288814/tpl-check-if-task-was-faulted-in-oncompleted-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!