alansiqueira27
alansiqueira27

Reputation: 8506

BackgroundWorker reportProgress in another class

I have a code similar to the last code in this link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

But the ComputeFibonacci method is inside another class, so my doWork method would be this:


private void backgroundWorker1_DoWork(object sender, 
            DoWorkEventArgs e)
        {   
            BackgroundWorker worker = sender as BackgroundWorker;

            e.Result = new MyClass().ComputeFibonacci((int)e.Argument, worker, e);
        }

My code locks the application for ever when I use the worker.ReportProgress(percentComplete); inside the fibonaci method which is in another class. I think the problem is that the backgroundWorker1_ProgressChanged is inside another class, instead of MyClass.

What should I do please?

If I put the fibonaci method inside the same class, the problem won't occur. But in my case, doesn't make sence to put the code inside the same class.

Thanks

Upvotes: 1

Views: 5500

Answers (2)

micahtan
micahtan

Reputation: 19160

The ProgressChanged event handler should be in the same class as the DoWork event handler.

In your ComputeFibonacci method, you would pass in the BackgroundWorker object, and call the worker.ReportProgress method. This should call the ProgressChanged delegate.

Upvotes: -3

brunnerh
brunnerh

Reputation: 184526

Make MyClass fire an event:

public class MyClass
{
    public event ProgressChangedEventHandler ProgressChanged;

    protected virtual void OnProgressChanged(int progress)
    {
        if (ProgressChanged!= null)
        {
            ProgressChanged(this, new ProgressChangedEventArgs(progress, null));
        }
    }

    public int ComputeFibonacci(int input)
    {
        //<Calculate stuff>
        OnProgressChanged(currentProgress);
        //...
        return output;
    }
}
private void backgroundWorker1_DoWork(object sender,
    DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    var myClass = new MyClass();
    myClass.ProgressChanged += (s, pe) => worker.ReportProgress(pe.ProgressPercentage);
    myClass.ComputeFibonacci((int)e.Argument);
}

Something like that.

Upvotes: 4

Related Questions