ricki
ricki

Reputation: 159

Background worker

If i have a set of actions i want to run in a background worker based on a certain condition and i have 10 conditions, for example

if(a)
    BackgroundWorker doA = new backgroundworker()
if(b) 
    BackgroundWorker doB = new backgroundworker()
if(c) 
    BackgroundWorker doC = new backgroundworker()
if(d) 
    BackgroundWorker doD = new backgroundworker()
...
...

each of those background workers will require a dowork, runworkercompleted etc.... is there anyway to avoid that so it makes the code less messy/clutered as some of those methods might be quite big?

thanks

Upvotes: 1

Views: 622

Answers (3)

Ray
Ray

Reputation: 46555

Why don't you pass in the object that needs evaluating to the BackgroundWorker and the BackgroundWorker can use it to determine what to do?

Upvotes: 0

biju
biju

Reputation: 18000

You can consider using a single backgroundworker and passing an argument to it.Using this argument in the DoWork method you can determine which block of code to work.Check this thread

Sending Arguments To Background Worker?

Upvotes: 1

AbdouMoumen
AbdouMoumen

Reputation: 3854

You should use Task from the System.Threading.Tasks namespace instead, it's very simple and easy to use.

To start a task, you can simply use: Task.Factory.StartNew() passing a method or a lambda expression as a parameter. you get back a Task object that you can use for continuation, getting the result back, etc.

Upvotes: 3

Related Questions