如何在单击取消按钮时取消 DoWork 中的所有方法?

How to cancel all methods in DoWork while clicking cancel button?

我知道这不是关于取消的第一个问题 BackGroundWorker 但我没有找到解决问题的答案。

如果我单击警告框中的 cancel(中止)按钮,我需要终止 Dowork 方法中的所有方法。这里 QueryexecutionsettingForControl 方法是另一种 class 方法。如果我在任何时候给出中止选项,它将需要终止所有方法。

如何实现?

我当前的代码是:

CancelSupportedBackgroundWorker backGroundWorker = new CancelSupportedBackgroundWorker {
    WorkerSupportsCancellation = true
};

AlertBox alertBox = new AlertBox
{
    WaitingText = "Loading",
    WaitingHeaderText = "Loading Indicator",
};
alertBox.IsBusy = true;
alertBox.AbortButton.Click += (obj, arg) =>
{
    backGroundWorker.CancelAsync();
    alertBox.AbortButton.IsEnabled = false;
    backGroundWorker.Abort();
    backGroundWorker.Dispose();
};
backGroundWorker.DoWork += (obj, arg) =>
{
    App.Current.Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(
        delegate ()
        {
            try
            {
                query.SettingForControl();
                query.QueryExecution(connectionstring);
                alertBox.AbortButton.IsEnabled = false;

                if (backGroundWorker.CancellationPending)
                    arg.Cancel = true;
            }
            catch (ThreadAbortException)
            {
                Dispatcher.Invoke(() =>
                {
                    alertBox.IsBusy = false;
                }, 
                System.Windows.Threading.DispatcherPriority.Background);
                arg.Cancel = true;
            }   
        })
    );
};
backGroundWorker.RunWorkerCompleted += (obj, arg) =>
{
    if (arg.Cancelled)
    {
        alertBox.IsBusy = false;
        return;
    }
    alertBox.IsBusy = false;    
};
backGroundWorker.RunWorkerAsync(this);

官方的方法是使用CancellationTokenSource。您将在 AlertBox 中创建 CancellationTokenSource 的实例,然后将 Token 从源传递到 BackgroundWorker

然后 BackgroundWorker 会将令牌传递给它调用的所有方法。

您必须修改所有涉及的方法以接收 CancellationToken 作为参数,并通过调用其 ThrowIfCancellationRequested 方法定期检查令牌的取消状态。还要检查 DoWork 处理程序本身中令牌的状态。

然后您可以通过调用 CancellationTokenSource 上的 Cancel 方法来取消操作。