0

我有一个应用程序,它有几种需要很长时间才能完成的方法。我正在使用后台工作人员来运行这些方法并保持我的 UI 响应。我的方法看起来像

public void DoSomething()
{
   while( HaveMoreWork )
   {
     // do work
   }
}

现在我希望 UI 能够随时取消它,所以我改变了我的方法来像这样使用 Backgroundworker

public void DoSomething(Backgroundworker worker)
{

   while( HaveMoreWork && !worker.CancelationPending )
   {
     // do work
   }
}

我的问题是,有没有更好的方法来做到这一点。似乎将 Backgroundwoker 作为参数传递给所有这些方法有点混乱。对此的最佳做法是什么?

4

2 回答 2

1

我正在使用全局变量

private BackgroundWorker _bwSearch = new BackgroundWorker();

private void InitializeBackgroundWorker()
{
     _bwSearch = new BackgroundWorker();
     _bwSearch.WorkerSupportsCancellation = true;
     _bwSearch.DoWork += bwSearch_DoWork;
     _bwSearch.RunWorkerCompleted += bwSearch_RunWorkerCompleted;
}

当点击停止按钮时

 private void btnCancel_Click(object sender, EventArgs e)
 {
      _bwSearch.Abort();
 }

更新: 我也在使用从 BackgroundWorker 继承的这个简单的帮助类

public class AbortableBackgroundWorker : BackgroundWorker
    {
        private Thread _workerThread;

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            _workerThread = Thread.CurrentThread;

            try
            {
                base.OnDoWork(e);
            }
            catch (ThreadAbortException)
            {
                e.Cancel = true;

                Thread.ResetAbort();
            }
        }

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

                _workerThread = null;
            }
        }
    }
于 2012-07-11T15:48:22.130 回答
0
public class DoSomethingService
{
    private volatile bool _stopped = false;

    public void Start(object socketQueueObject)
    {
        while (!_stopped)
        {
            ...
        }
    }

    public void Stop()
    {
        _stopped = true;
    }
}

...

var doSomethingService = DoSomethingService();
doSomethingService.Start();
...
doSomethingService.Stop();
于 2012-07-11T15:44:27.497 回答