gpt4 book ai didi

c# - 如何在 C# 中停止正在运行的任务

转载 作者:行者123 更新时间:2023-11-30 21:38:04 25 4
gpt4 key购买 nike

我有一个正在运行的任务,需要制作一个用户可以随时停止正在运行的任务的功能。我试着 token.Cancel();但还是没用。

这是我的代码:

var task = new Task(new Action(Method), tokenSource2.Token);
var cToken = tokenSource2.Token;
cToken.Register(() => cancelNotification());

// code to stop the running task .. button click event

if (tokenSource2 != null)
{

tokenSource2.Cancel();


}

最佳答案

我相信要使取消 token 起作用,作为任务主体调用的方法需要接受取消 token 并不断检查它是否已在每个逻辑步骤之间被取消。 See here for more details .

此示例摘自该文档并概述了如何检查取消 token 的状态。

using System;
using System.Threading;

public class Example
{
public static void Main()
{
// Create the token source.
CancellationTokenSource cts = new CancellationTokenSource();

// Pass the token to the cancelable operation.
ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token);
Thread.Sleep(2500);

// Request cancellation.
cts.Cancel();
Console.WriteLine("Cancellation set in token source...");
Thread.Sleep(2500);
// Cancellation should have happened, so call Dispose.
cts.Dispose();
}

// Thread 2: The listener
static void DoSomeWork(object obj)
{
CancellationToken token = (CancellationToken)obj;

for (int i = 0; i < 100000; i++) {
if (token.IsCancellationRequested)
{
Console.WriteLine("In iteration {0}, cancellation has been requested...",
i + 1);
// Perform cleanup if necessary.
//...
// Terminate the operation.
break;
}
// Simulate some work.
Thread.SpinWait(500000);
}
}
}
// The example displays output like the following:
// Cancellation set in token source...
// In iteration 1430, cancellation has been requested...

关于c# - 如何在 C# 中停止正在运行的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com