5
如何使用CancellationToken属性?
与前面的RulyCanceler类代码相比,我想使用来运行代码 CancellationTokenSource。 如取消令牌中所述,如何使用它,即不引发/捕捉异常?我可以使用IsCancellationRequested财产吗? 我试图这样使用它: cancelToken.ThrowIfCancellationRequested(); 和 try { new Thread(() => Work(cancelSource.Token)).Start(); } catch (OperationCanceledException) { Console.WriteLine("Canceled!"); } 但这cancelToken.ThrowIfCancellationRequested();在方法中产生了运行时错误Work(CancellationToken cancelToken): System.OperationCanceledException was unhandled Message=The operation was canceled. Source=mscorlib StackTrace: at System.Threading.CancellationToken.ThrowIfCancellationRequested() at _7CancellationTokens.Token.Work(CancellationToken cancelToken) in C:\xxx\Token.cs:line 33 at _7CancellationTokens.Token.<>c__DisplayClass1.<Main>b__0() in C:\xxx\Token.cs:line 22 at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, …