gpt4 book ai didi

c# - 取消任务

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:43 24 4
gpt4 key购买 nike

我需要取消使用 dll 中长时间运行的方法的任务(本例中为 MethodFromDll())我在哪里可以调用 cancellationToken.ThrowIfCancellationRequested() 方法来取消此任务?

tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;

t = Task.Factory.StartNew(() => {
try {
...some code
// I need to cancel this task manually if method not answer
// or there is no wish to wait
MethodFromDll();
...some code
} catch {
...some code
}
}, cancellationToken);

最佳答案

在您的 CancellationTokenSource 上调用 Cancel 并注册回调

tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;

return Task.Factory.StartNew(() =>
{
try
{
cancellationToken.Register(() =>
{
//call api method to stop long running method
});
//...some code
}
catch
{

}
}, cancellationToken);

关于c# - 取消任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32205940/

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