WinRT 将令牌分配给异步任务
WinRT assigning a token to asynchronous task
我想知道为异步任务分配令牌的原因,如下例所示:
var ctSource = new CancellationTokenSource();
Task.Factory.StartNew(() => doSomething(), ctSource.Token);
MSDN 文档坚持将令牌传递给 运行 方法并将其分配给任务,但对我来说,这似乎是一种不自然的重复。
如果给任务分配了令牌,是否意味着ctSource.Cancel()
自动触发TaskCancelledException
任务?
有没有办法从任务中检索分配的令牌(除了将其作为参数发送)?
如果两者都不是,那么为任务分配令牌的原因是什么?
- If a token is assigned to a task, does it mean, that ctSource.Cancel()automatically triggers TaskCancelledException for the task?
任务可以随时开始,现在或以后。因此,如果碰巧令牌在该任务开始之前有取消请求,调度程序本身将抛出 OperationCanceledException
,并且您的操作 () => doSomething()
永远不会被调用。因此,令牌被传递给工厂,而不是任务。这由 StartNew(...)
方法使用。
- Is there a way to retrieve the assigned token from the task (other than by sending it as an argument) ?
没有。任务不知道 CancellationToken
,只知道执行。任务不会自动取消。任务中的函数 运行 负责在请求取消时退出。
您是 CancellationTokenSource
的所有者。所以传给需要的人吧
Task.Factory.StartNew(() => doSomething(ctSource.Token), ctSource.Token);
如果您不是 doSomething()
(来自第 3 方 DLL)的所有者,则您无法取消该操作,除非它接受 CancellationToken
。
我想知道为异步任务分配令牌的原因,如下例所示:
var ctSource = new CancellationTokenSource();
Task.Factory.StartNew(() => doSomething(), ctSource.Token);
MSDN 文档坚持将令牌传递给 运行 方法并将其分配给任务,但对我来说,这似乎是一种不自然的重复。
如果给任务分配了令牌,是否意味着
ctSource.Cancel()
自动触发TaskCancelledException
任务?有没有办法从任务中检索分配的令牌(除了将其作为参数发送)?
如果两者都不是,那么为任务分配令牌的原因是什么?
- If a token is assigned to a task, does it mean, that ctSource.Cancel()automatically triggers TaskCancelledException for the task?
任务可以随时开始,现在或以后。因此,如果碰巧令牌在该任务开始之前有取消请求,调度程序本身将抛出 OperationCanceledException
,并且您的操作 () => doSomething()
永远不会被调用。因此,令牌被传递给工厂,而不是任务。这由 StartNew(...)
方法使用。
- Is there a way to retrieve the assigned token from the task (other than by sending it as an argument) ?
没有。任务不知道 CancellationToken
,只知道执行。任务不会自动取消。任务中的函数 运行 负责在请求取消时退出。
您是 CancellationTokenSource
的所有者。所以传给需要的人吧
Task.Factory.StartNew(() => doSomething(ctSource.Token), ctSource.Token);
如果您不是 doSomething()
(来自第 3 方 DLL)的所有者,则您无法取消该操作,除非它接受 CancellationToken
。