开发者

Assign work in backgroundworker_DoWork() according to condition

开发者 https://www.devze.com 2023-01-17 17:33 出处:网络
In a Winform application,I want to use a single backgroundworker (or may be one for each form) to do di开发者_如何学Cfferent tasks on different events. For eg: Search, Loading Data in grid, opening ne

In a Winform application,I want to use a single backgroundworker (or may be one for each form) to do di开发者_如何学Cfferent 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消