所以我不明白的是以下应用程序中发生了什么:
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);
}
}
在第一个示例中,我认为程序应该执行该行:Console.WriteLine("Object is " + ob);
然后当它中止时t.Wait(1000)
没有任何行。
程序的输出是:
TaskVersion:
TaskWithCancelationTokenVersion:
Object is something
ThreadVersion:
Object is something
所以task.Wait()
这只是一种突然关闭线程并回滚它所做的事情的方法吗?