Home:ALL Converter>BackgroundWorker reportProgress in another class

BackgroundWorker reportProgress in another class

Ask Time:2011-04-28T01:56:36         Author:alansiqueira27

Json Formatter

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

Author:alansiqueira27,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/5808427/backgroundworker-reportprogress-in-another-class
H.B. :

Make MyClass fire an event:\n\npublic class MyClass\n{\n public event ProgressChangedEventHandler ProgressChanged;\n\n protected virtual void OnProgressChanged(int progress)\n {\n if (ProgressChanged!= null)\n {\n ProgressChanged(this, new ProgressChangedEventArgs(progress, null));\n }\n }\n\n public int ComputeFibonacci(int input)\n {\n //<Calculate stuff>\n OnProgressChanged(currentProgress);\n //...\n return output;\n }\n}\n\n\n\n\nprivate void backgroundWorker1_DoWork(object sender,\n DoWorkEventArgs e)\n{\n BackgroundWorker worker = sender as BackgroundWorker;\n\n var myClass = new MyClass();\n myClass.ProgressChanged += (s, pe) => worker.ReportProgress(pe.ProgressPercentage);\n myClass.ComputeFibonacci((int)e.Argument);\n}\n\n\nSomething like that.",
2011-04-27T18:02:00
yy