当我阅读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();
}
}
我做错了什么?