我有一个繁重的进程在其体内运行的任务。此外,我们无法访问此方法的主体(繁重的进程),我们必须等到完成该进程。
现在我的问题是,如何在不中断任务的情况下取消,以便不检查其中的任何值?
我的代码是这样的:
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
{ }
}
运行后我可以取消繁重的过程吗?