简体   繁体   中英

Get Get Value Back from a Delegate executed within a Backgroundworker?

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"?

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM