我对如何使用条件Continuations的任务感到困惑.
如果我有一个任务,然后我想继续处理成功和错误的任务,然后等待那些完成.
void FunctionThrows() {throw new Exception("faulted");}
static void MyTest()
{
var taskThrows = Task.Factory.StartNew(() => FunctionThrows());
var onSuccess = taskThrows.ContinueWith(
prev => Console.WriteLine("success"),
TaskContinuationOptions.OnlyOnRanToCompleted);
var onError = taskThrows.ContinueWith(
prev => Console.WriteLine(prev.Exception),
TaskContinuationOptions.OnlyOnFaulted);
//so far, so good
//this throws because onSuccess was cancelled before it was started
Task.WaitAll(onSuccess, onError);
}
Run Code Online (Sandbox Code Playgroud)
这是执行任务成功/失败分支的首选方式吗?另外,我应该如何加入所有这些任务,假设我已经创建了一长串的延续,每个延续都有自己的错误处理.
//for example
var task1 = Task.Factory.StartNew(() => ...)
var task1Error = task1.ContinueWith( //on faulted
var task2 = task1.ContinueWith( //on success
var task2Error = task2.ContinueWith( //on faulted
var task3 = …Run Code Online (Sandbox Code Playgroud)