[英]how to add a Cancellation Token to a Task?
I am getting introduced to Task, and got this far: 我将被介绍给Task,并且到此为止:
In Main: 在主要:
Task<double> t = Task.Run(TW.DoingMegaFlops_Async);
Where in class TW: TW班级:
public async Task<double> DoingMegaFlops_Async()
{...await ...; return 0.0;}
My concept console app builds and runs just fine. 我的概念控制台应用程序可以正常构建和运行。 The problem is how to expand this with a
Cancellation Token
. 问题是如何使用
Cancellation Token
来扩展它。 I tried this: 我尝试了这个:
CancellationTokenSource wtokenSource= new CancellationTokenSource();
Task.Run(TW.DoingMegaFlops_Async(wtokenSource.Token), wtokenSource.Token);
and in the TW class: 在TW类中:
public async void DoingMegaFlops_Async(CancellationToken wtoken)
{...await...; return;}
The build error in Main is: Main中的生成错误是:
Cannot convert from 'void' to 'System.Action'
I have already fooled around with casting to (Action), but with no avail. 我已经愚弄了对(Action)的转换,但无济于事。 Actually, I do not really understand what I am doing here, so would like to learn from the forum.
实际上,我不太了解自己在这里做什么,因此想向论坛学习。
As you see from the code snippets, I already cut down on the interface of the Async method by going to a return type of void. 从代码片段中可以看到,我已经通过返回void类型来缩减Async方法的接口。 Don't know if that actually made things easier.
不知道这是否真的使事情变得容易。
Task.Run(TW.DoingMegaFlops_Async)
is "Method Group" shorthand for Task.Run(() => TW.DoingMegaFlops_Async())
- it's allowed because you're calling a method with no parameters. Task.Run(TW.DoingMegaFlops_Async)
是Task.Run(() => TW.DoingMegaFlops_Async())
“方法组”的简写-之所以允许,是因为您正在调用没有参数的方法。
When calling a method with parameters, though, you must include it: 但是,在调用带有参数的方法时,必须包括它:
Task.Run(() => TW.DoingMegaFlops_Async(wtokenSource.Token), wtokenSource.Token);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.