1

当我阅读Jeffrey Richter, CLR via C#时,我发现了这个例子。预计会根据 执行新任务TaskContinuationOptions,但事实并非如此。我以为我会有下一个结果:

Finished, SUM=5050

但是我有空输出,即使我添加throw exceptionSum函数,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();            
    }
}

我做错了什么?

4

1 回答 1

2

实际上,您正确设置了延续,但您无法在控制台上看到结果,因为应用程序之前存在:

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

应用程序不会等待后台线程完成 - 当应用程序的主线程完成它的工作时它将被关闭(您的 Main 方法)

编辑另一种选择是等到后台线程(继续线程)完成并保持应用程序处于活动状态:

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
于 2013-08-02T09:22:54.140 回答