Saw this in some code but didn’t make sense to me, So I was wondering if even it is a correct way of utilizing backgreound worker?
it is used like this on Form_Load event:
BackgroundWorker asyncWorker = new BackgroundWorker();
asyncWorker.DoWork += new DoWorkEventHandler(AsynchDoWork);
asyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(AsynchCompleted);
asyncWorker.RunWorkerAsync();
// a for each loop that can take some time to populate a combobx on the form
Also, is there a better alternative on achieving the same goal? other than backgroundworker?
I would use the Task Parralell Library for this. A good into tutorial is Task Parallel Library: 1 of n. To update a combo box following the result of some background task you could do something like this
Here the
uiSchedulerlets you update the ui thread from within the continuation delegate which fires when the antecedent task completes (either successfully or otherwise).The continuation also acts as an exception handler in this case to catch any
AggregateExceptionsthey may be thrown from the background thread.I hope this helps.