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 backgrou开发者_运维问答ndworker()
...
...
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
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.
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?
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?
精彩评论