Beh*_*zad 2 .net c# parallel-processing task-parallel-library cancellationtokensource
我有一个重型过程的任务在那个体内运行.另外,我们无法访问此方法的主体(繁重的过程),我们必须等到完成该过程.
现在我的问题是,如何在不中断任务的情况下取消,以便我不检查任何值?
我的代码是这样的:
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
{ }
}
Run Code Online (Sandbox Code Playgroud)
在运行之后我可以取消繁重的过程吗?
如果你无法控制长时间运行的方法,那么合作取消就不会起作用.您可以做的是将繁重的作业卸载到不同的进程,并在后台线程中监视进程:
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();
}
});
}
Run Code Online (Sandbox Code Playgroud)
现在,当您取消时,您将调用我们终止进程的回调:
private void CancelProcess()
{
CTS.Cancel();
}
Run Code Online (Sandbox Code Playgroud)