C# 如何取消并发的繁重任务?
我有一个在它体内运行的沉重过程。此外,我们无法访问此方法的主体(繁重的过程),必须等到过程完成 现在我的问题是,如何在不中断任务的情况下取消,以便不检查任务中的任何值 我的代码如下:C# 如何取消并发的繁重任务?,c#,.net,parallel-processing,task-parallel-library,cancellationtokensource,C#,.net,Parallel Processing,Task Parallel Library,Cancellationtokensource,我有一个在它体内运行的沉重过程。此外,我们无法访问此方法的主体(繁重的过程),必须等到过程完成 现在我的问题是,如何在不中断任务的情况下取消,以便不检查任务中的任何值 我的代码如下: private CancellationTokenSource CTS = new CancellationTokenSource(); public void CallMyMethod(CancellationTokenSource cts) { // // Several methods t
private CancellationTokenSource CTS = new CancellationTokenSource();
public void CallMyMethod(CancellationTokenSource cts)
{
//
// Several methods they call each other. And pass tokens to each other.
MyProcess(cts);
}
private void MyProcess(CancellationTokenSource cts)
{
CancellationToken token = cts.Token;
Task.Run(() =>
{
token.ThrowIfCancellationRequested(); // Work just when ThrowIfCancellationRequested called. and check that again
if (token.IsCancellationRequested) // Must be checked every time, and after the investigation not work.
return;
// My long time process
HeavyProcess(); // We have no access to the body of this method
}, token);
}
private void CancelProcess()
{
try
{
//
// I want to cancel Now, Just Now not after HeavyProcess completion or checking token again!
//
CTS.Cancel();
CTS.Token.ThrowIfCancellationRequested();
}
catch
{ }
}
运行之后,我可以取消繁重的进程吗?如果您无法控制长时间运行的方法,那么协作取消将不起作用。您可以将繁重的工作卸载到另一个进程,并在后台线程中监视该进程:
private void MyProcess(CancellationTokenSource cts)
{
cts.Token.ThrowIfCancellationRequested();
// Move the heavy work to a different process
var process = Process.Start(new ProcessStartInfo { /* */ });
// Register to the cancellation, where if the process is still
// running, kill it.
cts.Token.Register(() =>
{
if (!process.HasExited)
{
process.Kill();
}
});
}
现在,当您取消时,您将调用回调,我们将在其中终止流程:
private void CancelProcess()
{
CTS.Cancel();
}
放弃正在运行的
任务
可以吗,或者您需要完全中止它吗?只需在运行时中止它,我将不再继续该工作!评论不用于扩展讨论;这段对话已经结束。