取消后台工作人员任务

时间:2017-07-28 06:11:16

标签: c# multithreading visual-studio backgroundworker

我有一个执行耗时任务的后台工作人员,但我遇到了取消问题,因为我可以设法只标记取消而不是实际终止该过程。为了解决它,我试图在我要退出的重函数中加入一些检查点,但它看起来效率不高。 我的代码看起来像这样:

在重要功能的某些方面,我把这两行:

if (general.backgroundWorker1.CancellationPending)
{ 
   return;
}

private void button4_Click(object sender, EventArgs e) //button invokes heavy function
{
    if (!backgroundWorker1.IsBusy)
        backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    heavyFunction(this);
    if (backgroundWorker1.CancellationPending)
    {
        e.Cancel = true;
        return;
    }
}

private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        statusLabel.Text = "Status: cancelled";
    }
    else if (e.Error != null)
    {
        statusLabel.Text = "ERROR!";
    }
    else
    {
        some code;
    }
}

private void cancelSDoutLoop_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }
}

1 个答案:

答案 0 :(得分:0)

取消可能是一个复杂的功能来实现,往往留作事后的想法。

如果您要取消heavyFunction(可能应该是longRunningFunction;),则必须取消注意。你说你已经放了检查点,这是有道理的。

您可以尝试使用更多接受取消令牌的可取消方法调用。例如,Task.Delay有两个重载:

Delay(TimeSpan)

Delay(TimeSpan, CancellationToken)

另一种策略是将方法拆分为更小,更短的任务。

最后,取消操作不必立即进行。 你可能会以#34;取消......"等待停止工作的好时机的状态。

相关问题