如何取消并发的重任务

本文关键字:并发 任务 取消 何取消 | 更新日期: 2023-09-27 17:49:46

我有一个任务重进程运行在那的身体。此外,我们不能访问这个方法的主体(重进程),我们必须等到进程完成。

现在我的问题是,我如何在不中断任务的情况下取消任务,以便我不检查其中的任何值?

我的代码如下:

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();
}