private static void Work(RulyCanceler canceler) { while (true) { canceler.ThrowIfCancellationRequested(); // 检查CancellationRequest是否为true try { OtherMethod(canceler); } finally { // any required cleanup. } } }
static void Main(string[] args) { var canceler = new RulyCanceler(); new Thread(() => { try { Work(canceler); } catch (OperationCanceledException) { Console.WriteLine("Canceled!"); } }).Start(); Thread.Sleep(5000); canceler.Cancel(); // cancel掉操作. }
private static void OtherMethod(RulyCanceler canceler) { // Do stuff... canceler.ThrowIfCancellationRequested(); }