【问题标题】:How do I cancel a concurrent heavy Task?如何取消并发的繁重任务?
【发布时间】:2015-05-20 06:05:24
【问题描述】:

我有一个 Task 通过繁重的进程在其体内运行。另外,我们无法访问这个方法的主体(繁重的进程),我们必须等到完成这个过程。

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

我的代码是这样的:

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 
    { }
}

运行后我可以取消繁重的进程吗?

【问题讨论】:

  • 丢弃正在运行的Task 可以吗,还是需要完全中止它?
  • 只要在运行时中止它,我就不会再继续那个工作了!

标签: c# .net parallel-processing task-parallel-library cancellationtokensource


【解决方案1】:

如果您无法控制长时间运行的方法,那么协作取消将不起作用。您可以做的是将繁重的工作卸载到不同的进程,并在后台线程中监视进程:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2012-09-19
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
相关资源
最近更新 更多