tags:

views:

29

answers:

1

I have a Windows Forms App that loads a dll @ runtime and executes a method using a Delegate. The work that is done is basically uploading files into a WebApp and is time consuming. I would like to use the BackgroundWorker to run it in the Background and then pop up a Form letting the user know that the upload completed and how many files were successfully uploaded. But I am not sure how to get the int that is returned by the Method Called via the delegate from within a BackgroundWorker.

So here is the code that does the work

private int UploadDocs(object sender, DoWorkEventArgs e)
        {
            Assembly a = Assembly.LoadFrom(this.txtReleaseScript.Text);
            Type type = a.GetType("FileReleaseHandler", true);
            string[] param = new string[8];
            //populate the array with parameters
            IFileReleaseHandler handler(IFileReleaseHandler)Activator.CreateInstance(type, param);
            ReleaseFileDelegate RFD = new ReleaseFileDelegate(handler.ReleaseFiles);
            int numberOfFilesUploaded = RFD.Invoke(Source, Dest);
            return numberOfFilesUploaded;
        }

And here is how I call it in a BackgroundWorker

private void btRelease_Click(object sender, EventArgs e)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(UploadDocs);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.ShowUploadResults);
            bw.RunWorkerAsync();
        }

The ShowUploadResults just opens a form to let the user know the upload process has completed. My question is how can I get the int that is returned from the UploadDocs Method and pass it into the ShowUploadResults Method so it can display something like "55 files were successfully uploaded"?

+4  A: 

Assign the result value to e.Result. It will then be available in your ShowUploadResults as e.Result. Quote from the MSDN docs:

"If your operation produces a result, you can assign the result to the DoWorkEventArgs.Result property. This will be available to the RunWorkerCompleted event handler in the RunWorkerCompletedEventArgs.Result property."

Stephen Cleary
+1 - For more info - http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx
Alex Humphrey