TPL:检查任务是否在 OnCompleted 事件中出错 [英] TPL: check if task was faulted in OnCompleted event
本文介绍了TPL:检查任务是否在 OnCompleted 事件中出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的任务:
var migrateTask = Task.Run(() =>
{
//do stuff
});
migrateTask.ConfigureAwait(true).GetAwaiter().OnCompleted(this.MigrationProcessCompleted);
如何在方法 MigrationProcessCompleted
中判断我是否在初始线程中出现异常或任务出错(在 do stuff 代码块中)?
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?
推荐答案
你永远不应该真正调用 .GetAwaiter()
它是为编译器使用而设计的.
You should never be really calling .GetAwaiter()
it is intended for compiler use.
如果你可以使用 await
你的代码就像
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.
}
这篇关于TPL:检查任务是否在 OnCompleted 事件中出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文