poco
poco

Reputation: 2995

Should i pass a Backgroundworker to method

I have an app that has several methods that take a long time to complete. I am using a backgroundworker to run these methods and keep my UI responsive. My methods look something like

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

Now i want the UI to be able to cancel this at any time so I have changed my methods to take a Backgroundworker like so

public void DoSomething(Backgroundworker worker)
{

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

My question is, is there a better way to do this. Seems like passing a Backgroundwoker as an argument to all these methods is a bit messy. What is best practice for this?

Upvotes: 0

Views: 94

Answers (2)

algreat
algreat

Reputation: 9002

I am using global variable

private BackgroundWorker _bwSearch = new BackgroundWorker();

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

when clicked on stop button

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

Updated: Also I am using this simple helper class that is inherited from 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;
            }
        }
    }

Upvotes: 1

Roman Asanov
Roman Asanov

Reputation: 297

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

Upvotes: 0

Related Questions