Whats the benefit of passing a CancellationToken as a parameter to Task.Run?(转载)
问:
Obviously I realize it enables me to cancel the task, but this code achieves the same effect without having to pass the token into Task.Run
What is the practical difference? Thanks.
Dim cts As New CancellationTokenSource Dim ct As CancellationToken = cts.Token Task.Run(Sub() For i = 1 To 1000 Debug.WriteLine(i) ct.ThrowIfCancellationRequested() Threading.Thread.Sleep(10) Next End Sub) cts.CancelAfter(500)
VS
Dim cts As New CancellationTokenSource Dim ct As CancellationToken = cts.Token Task.Run(Sub() For i = 1 To 1000 Debug.WriteLine(i) ct.ThrowIfCancellationRequested() Threading.Thread.Sleep(10) Next End Sub, ct) cts.CancelAfter(500)
答:
The API docs for Task.Run(Action, CancellationToken) has this remark:
If cancellation is requested before the task begins execution, the task does not execute. Instead it is set to the Canceled state and throws a TaskCanceledException exception.
So in your scenario, there isn't any practical difference because you wait 500 milliseconds before issuing the cancellation. In that time the task is scheduled, begins execution, and runs through the loop a number of times before the cancellation is issued, manifesting as an exception thrown from ct.ThrowIfCancellationRequested().
The difference between Task.Run(Action) and Task.Run(Action, CancellationToken) is more apparent with this modified version of your example:
Try Dim cts As New CancellationTokenSource Dim ct As CancellationToken = cts.Token cts.Cancel() Dim task As Task = Task.Run( Sub() Console.WriteLine("Started running your code!") ct.ThrowIfCancellationRequested() Console.WriteLine("Finished running your code!") End Sub, ct) task.Wait() Catch ex As AggregateException Console.Error.WriteLine("Caught exception: " & ex.InnerException.Message) End Try Console.WriteLine("Done, press Enter to quit.") Console.ReadLine()
In this scenario, Task.Run schedules the task to run, but also associates the cancellation token with that task. When we call task.Wait(), before the thread pool executes the task, it checks the cancellation token and notices that a cancellation has been issued on that token, so it decides to cancel before executing the task. So the output is:
Caught exception: A task was canceled. Done, press Enter to quit.
If you instead replace: End Sub, ct) with End Sub), then the thread pool isn't aware of the cancellation token, so even though you've issued a cancellation, it proceeds with executing the task, before your task code itself checks for cancellation. So the output is:
Started running your code! Caught exception: The operation was canceled. Done, press Enter to quit.
(You can see that the exception message is slightly different in these two cases as well.)
In summary, providing the cancellation token to the Task.Run method allows the thread pool itself to know if the task is cancelled before the thread pool gets a chance to execute the task. This allows the thread pool to save time and resources by not even bothering to start running the task.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架