Q:

Why Task canceled run again with new Task?

I have a example about Task. I start a new Task to do a LongTask and after I cancel the Task and after start a new Task to do a LongTask again. But the TaskA is run not normally. It run the work of Task canceled and new Task.
How to run a new Task immediately and the Task canceled don't run again ?
Here my codes:
class Program
    {
        private static CancellationTokenSource tokenSource = new CancellationTokenSource();
        static void Main(string[] args)
        {
            Program a = new Program();
            Task.Factory.StartNew(() => a.LongTask(), tokenSource.Token);
            Console.ReadLine();

            //After enter
            tokenSource.Cancel();
            //Create new CancellationTokenSource to make Task continue run
            tokenSource = new CancellationTokenSource();
            Task.Factory.StartNew(() => a.LongTask(), tokenSource.Token);
            Console.ReadLine();
        }

        public void LongTask()
        {
            StringBuilder display = new StringBuilder();
            while (!tokenSource.IsCancellationRequested)
            {
                display.Append("1");
                Console.WriteLine(display);
                Thread.Sleep(1000);
            }
        }
    }

A:

I will visualize what happens when the first task is sleeping
while (!tokenSource.IsCancellationRequested)
{
    display.Append("1");
    Console.WriteLine(display);
    Thread.Sleep(1000);
    // tokenSource.Cancel();
    // tokenSource = new CancellationTokenSource();
    // Task.Factory.StartNew second task
}

then after sleeping timeout, task #1 continues its loop to check tokenSource.IsCancellationRequested which is false (because this token is the new one).
Now you understand why two tasks are running that way. Let's try my code:
static void Main(string[] args)
{
    var a = new Program();
    var token = new CancellationTokenSource();
    Task t1 = Task.Factory.StartNew(() => a.LongTask("#1", token1.Token), token1.Token);

    Console.ReadLine();

    token1.Cancel();
    token = new CancellationTokenSource();
    Task.Factory.StartNew(() => a.LongTask("#2", token2.Token), token2.Token);
    Console.ReadLine();
}

public void LongTask(string name, CancellationToken killer)
{
    var display = new StringBuilder();
    while (!killer.IsCancellationRequested)
    {
        display.Append("1");
        Console.WriteLine("{0} says: {1}",name, display);
                Thread.Sleep(1000);
    }
}

The trick here is to give each task a different token other than share same static token instance.

