【发布时间】:2013-02-10 15:35:19
【问题描述】:
与前面的代码for class RulyCanceler相比,我想用CancellationTokenSource运行代码。
如Cancellation Tokens 中所述,我该如何使用它,即不抛出/捕获异常?我可以使用IsCancellationRequested 属性吗?
我尝试这样使用它:
cancelToken.ThrowIfCancellationRequested();
和
try
{
new Thread(() => Work(cancelSource.Token)).Start();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
}
但这在方法Work(CancellationToken cancelToken) 中对cancelToken.ThrowIfCancellationRequested(); 产生了运行时错误:
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, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
我成功运行的代码在新线程中捕获了 OperationCanceledException:
using System;
using System.Threading;
namespace _7CancellationTokens
{
internal class Token
{
private static void Main()
{
var cancelSource = new CancellationTokenSource();
new Thread(() =>
{
try
{
Work(cancelSource.Token); //).Start();
}
catch (OperationCanceledException)
{
Console.WriteLine("Canceled!");
}
}).Start();
Thread.Sleep(1000);
cancelSource.Cancel(); // Safely cancel worker.
Console.ReadLine();
}
private static void Work(CancellationToken cancelToken)
{
while (true)
{
Console.Write("345");
cancelToken.ThrowIfCancellationRequested();
}
}
}
}
【问题讨论】:
-
docs.microsoft.com/en-us/dotnet/standard/threading/… 有一些很好的例子,将
CancellationTokenSource与异步方法、长时间运行的方法与轮询以及使用回调一起使用。 -
This 文章根据您的具体情况显示您拥有和需要处理令牌的选项。
标签: c# multithreading asynchronous concurrency synchronization