var task = Task.Run(() =>
{
for (var i = 0; i < 100000; i++)
{
Console.WriteLine(i);
}
});
static CancellationTokenSource source = new CancellationTokenSource();
var task = Task.Run(() =>
{
for (var i = 0; i < 100000; i++)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
},source.Token);
CancellationTokenSource source = new CancellationTokenSource();
//注册一个线程取消后执行的逻辑
source.Token.Register(() =>
{
//这里执行线程被取消后的业务逻辑.
Console.WriteLine("-------------我是线程被取消后的业务逻辑---------------------");
});
var t = Task.Run(() =>
{
for (var i = 0; i < 100000; i++)
{
if (source.IsCancellationRequested)
{
return;
}
Thread.Sleep(100);
Console.WriteLine("当前thread={0} 正在运行 {1}", Thread.CurrentThread.ManagedThreadId,i);
}
}, source.Token);
Thread.Sleep(1000);
source.Cancel();
Console.Read();