Question

So what I don't understand is what happens in the following application:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("TaskVersion:");
        Task t = new Task(waitCB, "something");
        t.Wait(1000);

        Console.WriteLine("TaskWithCancelationTokenVersion:");
        CancellationTokenSource cts = new CancellationTokenSource();
        Task tct = new Task(waitCB, "something", cts.Token);
        tct.Start();
        Thread.Sleep(1000);
        cts.Cancel();

        Console.WriteLine("ThreadVersion:");
        Thread th = new Thread(waitCB);
        th.Start("something");
        Thread.Sleep(1000);
        th.Abort();
    }

    static void waitCB(object ob)
    {
        Console.WriteLine("Object is " + ob);
        Thread.Sleep(10000);
    }
}

At the first example I think that the program should execute the line: Console.WriteLine("Object is " + ob); and then when it will abort t.Wait(1000) there isn't any line.

The programs' output is:

TaskVersion:
TaskWithCancelationTokenVersion:
Object is something
ThreadVersion:
Object is something

So task.Wait() it's just a way to abruptly close a thread and it rollback what it has done?

Was it helpful?

Solution

I think your issues have nothing to do with cancellation or Wait(), you just forgot to Start() the first Task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top