执行操作时显示繁忙的加载程序

时间:2016-01-04 16:30:54

标签: c# .net wpf multithreading backgroundworker

我修改了后台工作人员private AbortableBackgroundWorker _worker;

public class AbortableBackgroundWorker : BackgroundWorker
{
    //Internal Thread
    private Thread _workerThread;

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        try
        {
            base.OnDoWork(e);
        }
        catch (ThreadAbortException)
        {
            e.Cancel = true; //We must set Cancel property to true! 
            Thread.ResetAbort(); //Prevents ThreadAbortException propagation 
        }
    }

    public void Abort()
    {
        if (_workerThread != null)
        {
            _workerThread.Abort();
            _workerThread = null;
        }
    }
}

并且有init BgWorker

的方法
private void BusyLoader(Action doWorkAction)
    {
        if (_worker == null)
        {
            _worker = new AbortableBackgroundWorker();
            _worker.WorkerReportsProgress = true;
            _worker.WorkerSupportsCancellation = true;
            _worker.DoWork += (sender, e) => _worker_DoWork(sender, e, doWorkAction);
            _worker.RunWorkerCompleted += _worker_RunWorkerCompleted;
        }

        if (!_worker.IsBusy)
            _worker.RunWorkerAsync();
    }

private void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            loadingPanel.StopSpin();
            _worker.Abort();
            _worker.Dispose();
        }

        private void _worker_DoWork(object sender, DoWorkEventArgs e, Action action)
        {
            loadingPanel.StartSpin();
            this.Dispatcher.Invoke(action);
        }

当我调用方法BusyLoader时,我想传递一个应该执行的Action,此时应显示繁忙的指示符。

我试过了。它似乎有用,但只适用于BusyLoader的第一次调用。因为_worker.DoWork具有相同的方法,正如我所理解的那样。

如何为_worker.DoWork的每次新通话设置更改BusyLoader方法?或者像这样传递Action是不好的方法?

1 个答案:

答案 0 :(得分:0)

你说它有帮助所以会发表评论作为答案

_worker在第二次调用时不为null,因此_worker_DoWork未重新定义。尝试删除和添加。