views:

25

answers:

1

In a Winform application,I want to use a single backgroundworker (or may be one for each form) to do different tasks on different events. For eg: Search, Loading Data in grid, opening new forms, sending emails, File transfer etc.

How can i manage all this in backgroundWorker_DoWork() and backgroundWorker_RunWorkerCompleted() events?

What is the optimum way/ best practice to do this?

+2  A: 

Usually, I end up caling the worker with a parameter, like this:

backgroundWorker.RunWorkerAsync(<some argument here>);

Then inside your DoWork method, you can retrieve the argument from e.Argument, and according to what the argument is, you know what you want to do with it.

If you don't need the argument for anything else, you can make an enum with the values you need, like Search, Load and so forth and pass that in, and then check that value inside DoWork to choose what you want to do. Remember that you have to cast back to the enum inside Dowork since e.Argument is an object.

Regarding RunWorkerCompleted, you can populate e.Result with a value inside DoWork, and retrieve it inside the RunWorkerCompleted method as well.

This is the best way of doing it, and will be thread safe all the way.

Øyvind Bråthen