I have a Task by heavy process runs in that's body. In addition, we have no access to the body of this method (heavy process) and we must wait until to completion the process.
Now my question is, how do I cancel without interrupting the task so that I do not check any value in it?
My codes like this:
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
{ }
}
Can I cancel the heavy process after that running ?
If you can't control the long running method, then cooperative cancellation isn't going to work. What you can do is offload the heavy job to a different process, and monitor on the process in a background thread:
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();
}
});
}
And now, when you cancel, you invoke the callback where we terminate the process:
private void CancelProcess()
{
CTS.Cancel();
}