Basic BackgroundWorker usage with parameters

Chris picture Chris · Apr 26, 2011 · Viewed 43.2k times · Source

My process intensive method call that I want to perform in a background thread looks like this:

object.Method(paramObj, paramObj2);

All three of these objects are ones I have created. Now, from the initial examples I have seen, you can pass an object into a backgroundworker's DoWork method. But how should I go about doing this if I need to pass additional parameters to that object, like I'm doing here? I could wrap this in a single object and be done with it, but I thought it would be smart to get someone else's input on this.

Answer

mservidio picture mservidio · Apr 26, 2011

You can pass any object into the object argument of the RunWorkerAsync call, and then retrieve the arguments from within the DoWork event. You can also pass arguments from the DoWork event to the RunWorkerCompleted event using the Result variable in the DoWorkEventArgs.

    public Form1()
    {
        InitializeComponent();

        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

        object paramObj = 1;
        object paramObj2 = 2;

        // The parameters you want to pass to the do work event of the background worker.
        object[] parameters = new object [] { paramObj, paramObj2 };

        // This runs the event on new background worker thread.
        worker.RunWorkerAsync(parameters);
    }

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = e.Argument as object[];

        // do something.

        e.Result = true;
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        object result = e.Result;

        // Handle what to do when complete.                        
    }