Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...