我有一个页面有两个命令“RUN”“取消”。 我的问题:如何点击“取消”从任务进入“运行”取消?
TryTask:启动任务 取消:退出任务TryTask
CancellationTokenSource source = new CancellationTokenSource
private async Task TryTask()
{
Task<int> task = Task.Run(() => slowFunc(1, 2), source.Token);
// (A canceled task will raise an exception when awaited).
source.Cancel();
await task;
}
string someString = string.Empty;
public int slowFunc(int a, int b)
{
for (int i = 0; i < 200000000; i++)
{
someString += "a";
source.Cancel();
source.Token.ThrowIfCancellationRequested();
}
return a + b;
}
public async Task<ActionResult> Cancel()
{
"how cancel slow function"
}