问题
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