How to cancel a task with CancellationTokenSource

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    public static void Main()
    {
        var cts = new CancellationTokenSource();
        CancellationToken token = cts.Token;
        var t1 = Task.Run(() => {
            ulong sum = 0;
            for (ulong i = 0; i <= 1000000000UL; i++) {
                sum += i;
                if (token.IsCancellationRequested) {
                    Console.WriteLine("Task is canceled");
                    break;
                }
            }
            return sum;
        });
        var t2 = Task.Run(() => {
            Thread.Sleep(1000);
            cts.Cancel();
        });
        Task.WaitAll(t1, t2);
        Console.WriteLine("{0}", t1.Result);
    }
}

运行结果

Task is canceled
42868323482489736