【发布时间】:2015-02-14 13:58:23
【问题描述】:
我有这两种情况,但我不明白为什么会这样:
static void Main(string[] args)
{
Console.WriteLine("***Starting T1");
//run two tasks sequentially
Task t = FirstTask().ContinueWith(_ => SecondTask(), TaskContinuationOptions.OnlyOnRanToCompletion);
//register succeded and faulted continuations
t.ContinueWith(_ => Completion(), TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(_ => Faulted(), TaskContinuationOptions.OnlyOnFaulted);
Console.ReadLine();
Console.WriteLine("***Starting T2");
Task t2 = FirstTask().ContinueWith(_ => FaultTask(), TaskContinuationOptions.OnlyOnRanToCompletion);
t2.ContinueWith(_ => Completion(), TaskContinuationOptions.OnlyOnRanToCompletion);
t2.ContinueWith(_ => Faulted(), TaskContinuationOptions.OnlyOnFaulted);
Console.ReadLine();
Console.WriteLine("***Starting T3");
Task t3 = FirstTask().ContinueWith(ant => ant.ContinueWith(_ => FaultTask(), TaskContinuationOptions.OnlyOnRanToCompletion));
t3.ContinueWith(_ => Completion(), TaskContinuationOptions.OnlyOnRanToCompletion);
t3.ContinueWith(_ => Faulted(), TaskContinuationOptions.OnlyOnFaulted);
Console.ReadLine();
}
private static Task FirstTask()
{
return Task.Run(() =>
{
Console.WriteLine("Task 1");
Thread.Sleep(1000);
});
}
private static Task SecondTask()
{
return Task.Run(() =>
{
Console.WriteLine("Task 2");
Thread.Sleep(1000);
});
}
private static Task FaultTask()
{
return Task.Run(() =>
{
Console.WriteLine("Throw...");
Thread.Sleep(1000);
throw new ArgumentException();
});
}
private static void Completion()
{
Console.WriteLine("Complete");
}
private static void Faulted()
{
Console.WriteLine("Faulted");
}
在情况 1 中,事情按预期运行。但是,如果删除FirstTask()中的Sleep(),则不能保证任务按顺序运行。
在情况 2 中,Faulted() 处理程序未运行。我预计会发生这种情况,因为有一个未处理的异常。
在情况 3 中,在运行 Complete() 处理程序后引发异常。我对为什么会发生这种排序感到困惑。
基本上,我希望能够链接尽可能多的任务,并让它们在前一个任务完成后按顺序运行。一旦我创建了链,我将显示一个等待表单并将OnlyOnRanToCompletion、OnlyOnCancelled、OnlyOnFaulted 的延续注册到最终任务(阅读:全部完成)以关闭表单 - 显示成功或错误.
这是 MSDN 指的是那些不可用于多任务延续的选项吗?
【问题讨论】:
-
两个任务ran to completion。投票关闭,因为无法复制。一旦你用可以重现问题的代码更新问题,就会收回。我怀疑您的原始代码会设置一些您没有向我们展示的继续标志。
-
您的代码仍然不会显示所描述的行为。请在发布之前运行代码并测试自己。谢谢。
-
您能否发布演示问题所需的代码,以便我可以将代码复制并粘贴到控制台应用程序中并运行?目前第一个任务甚至无法编译。
-
@Simon,每当你调用
Task.Run(),你的任务已经开始了。因此,例如,在第一行代码中,您同时启动了两个任务 -
啊,是的,谢谢 Zruty
标签: c# multithreading task-parallel-library task continuations