当我阅读Jeffrey Richter, CLR via C#
时,我发现了这个例子。预计会根据TaskContinuationOptions
执行新任务,但事实并非如此。我以为我会有下一个结果:
Finished, SUM=5050
但我的输出为空,即使我在throw exception
函数中添加Sum
,也不会执行OnlyOnFaulted
。
class Program
{
public static Int32 Sum(Int32 n)
{
Int32 Sum = 0;
for (; n > 0; n--)
Sum += n;
return Sum;
}
static void Main(string[] args)
{
Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 100);
t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result), TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(tt => Console.WriteLine("Exception thrown"), TaskContinuationOptions.OnlyOnFaulted);
t.Start();
}
}
我做错了什么?
答案 0 :(得分:2)
实际上你正确设置了continuation,但是你无法在控制台上看到结果,因为应用程序存在于:
之前Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 100);
t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result),
TaskContinuationOptions.OnlyOnRanToCompletion);
t.ContinueWith(tt => Console.WriteLine("Exception thrown"),
TaskContinuationOptions.OnlyOnFaulted);
t.Start();
Console.ReadKey(); // keep app alive
应用程序不会等待后台线程完成 - 当应用程序的主线程完成它的工作时它将被关闭(你的主方法)
编辑另一个选择是等到后台线程(延续线程)完成并保持应用程序活着:
Task continuation =
t.ContinueWith(tt => Console.WriteLine("Finished, SUM={0}", tt.Result),
TaskContinuationOptions.OnlyOnRanToCompletion);
t.Start();
continuation.Wait(); // wait until continuation of task finishes
// exit application