c# - 如何安全地取消任务?
问题描述
所以我有这个任务,从点击一个按钮开始,我想知道,我如何安全地取消这个任务的循环?
private async Task RunAsync()
{
PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);
Random r = new Random();
while (true)
{
float pct = counter.NextValue() / 10f;
ServerCPU = pct.ToString("0.0");
await Task.Delay(2000);
}
}
单击启动任务循环的按钮后,我将如何取消它?
解决方案
与处理 s 时不同,如果没有它的合作,Thread
你不能取消/中止 a 。Task
这就是发挥作用CancellationToken
的地方。CancellationTokenSource
您应该在有意义的时候CancellationToken
进入并检查是否明确要求取消。RunAsync
在您的示例中,我可能会在每次迭代中都这样做:
private async Task RunAsync(CancellationToken ct)
{
PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", pServer.ProcessName, true);
Random r = new Random();
while (true)
{
ct.ThrowIfCancellationRequested();
float pct = counter.NextValue() / 10f;
ServerCPU = pct.ToString("0.0");
await Task.Delay(2000, ct);
}
}
在来电者网站上,您应该使用CancellationTokenSource
. 它将为您提供一种Token
传递RunAsync
方式以及一种触发取消的方式:
var cts = new CancellationTokenSource();
RunAsync(cts.Token);
// when you want to cancel it the task:
cts.Cancel();
您可以在托管线程中的取消中阅读有关该模式的更多信息。
推荐阅读
- python - 如何在 tensorflow 2.4.1 中设置优化器
- java - 如何为 Libgdx 类做 Junit 测试有图片和图片按钮
- react-intl - react-intl 作为 index.html 中的外部依赖项
- oracle - Oracle 如何通过 VIEW 实现 SQL 查询
- asp.net-mvc - 在 Mvc 中,使用 RedirectToAction("ReqAction", odetails) 得到错误为“输入不是有效的 base 64 字符串,因为它包含非 base 64 字符”
- css - 如何修复手机背景空白
- regex - 使用 Regex 从 SAP HANA 中的字符串中查找所有匹配项(十进制)
- unity3d - 如何在 Unity 中使用角色控制器添加碰撞?
- python - 更改 Selenium Firefox 驱动程序上的代理信息
- python - Python threading.Timer 有时会停止或暂停或冻结