1

I have some problem with backgroundWorker class. I wish I could within one function cancel Backroundworker and just after it start Backgroundworker dowork from scratch. It cause race and I have no idea how to change it. Is there any alternative to Backgroundworker in .net 3.5

Edited:

My code:

BackgroundWorker worker = new BackgroundWorker();

public void Func()
{

if(worker.IsBusy)
{
    worker.CancelAsync();
    worker = new BackgroundWorker();
}

View.Clear(); 

worker.WorkerSupportsCancellation = true;
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
    BackgroundWorker sender = s as BackgroundWorker;
    if(sender.CancellationPending)
    {
        args.Cancel = true;
        return;
    }

    View.Generate(Filter);
};

worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
    if(args.Error != null)
    {
        MessageBox.Show(args.Error.Message);
        return;
    }
    BackgroundWorker sender = s as BackgroundWorker;
    if(args.Cancelled )
    {
        View.Clear();
    }
};

worker.RunWorkerAsync();

}

The problem is: cancelAsync doesnt close worker at all and my view is generated in incorrect way

santBart
  • 2,466
  • 9
  • 43
  • 66
  • Probably looking into this worth http://stackoverflow.com/questions/6966573/how-is-backgroundworker-cancellationpending-thread-safe/6966759#6966759 – CharithJ Aug 17 '11 at 12:21
  • There are lots of alternatives. What are you trying to do? – Scott Weinstein Aug 17 '11 at 12:22
  • possible duplicate of [Reusing a BackgroundWorker, cancel and wait for it](http://stackoverflow.com/questions/7044938/reusing-a-backgroundworker-cancel-and-wait-for-it) – Hans Passant Aug 17 '11 at 13:21
  • The problem is: cancelAsync doesnt close worker at all and my "view" is generated in incorrect way – santBart Aug 17 '11 at 19:35

1 Answers1

2

You can use CancelAsync() and set WorkerSupportsCancellation to true and implements a loop to get CancellationPending

while(x.CancellationPending) { /*TODO*/ }
gandarez
  • 2,609
  • 4
  • 34
  • 47