1.概要
var cts = new CancellationTokenSource();
cts.Token.Register(fun);
CancellationToken = cts.Token
2.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.CompilerServices;
namespace ConsoleApp7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello word");
var cts = new CancellationTokenSource();
cts.Token.Register(fun);
new Task(()=> {
Thread.Sleep(50);
cts.Cancel(false);
}).Start();
try
{
ParallelLoopResult result = Parallel.For(0, 100, new ParallelOptions() {
CancellationToken = cts.Token
},x=> {
Console.WriteLine("start {0}",x);
Thread.Sleep(200);
Console.WriteLine("end -------- {0}", x);
});
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
static void fun() {
Console.WriteLine("token conceled");
}
}
}
运行效果