user1514077
user1514077

Reputation: 71

Winform running functions in parallel using backgroundworker possible?

I need to run four funcitons in parallel while keeping the UI responsive and reporting progress, is background worker the optimum way of doing this? How can I do this in winform?

Upvotes: 0

Views: 2483

Answers (3)

MoonKnight
MoonKnight

Reputation: 23833

You can do this using a BackgroundWorker but I would recommend the Task Parallel Library. For what you want you could use something like the following

TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
Task.Factory.StartNew(() =>
{
    Task.Factory.StartNew(() => { SomeMethod() }, atp);
    Task.Factory.StartNew(() => { SomeOtherMethod() }, atp); 
}).ContinueWith( cont => { Console.WriteLine("Finished!") });

This is using child tasks, here I have got two, you would use four. There are some limits to be aware of as the TPL uses the thread pool which has limits on the number of truly concurrent operations. Please check this https://stackoverflow.com/a/11229896/626442 and for more information on TPL and generic threading see

J. Albahari's Threading in C#

and (for TPL specifically)

This great tutorial

Upvotes: 2

Moble Joseph
Moble Joseph

Reputation: 657

Yes, Use Task Parallel Library. You could run parallel tasks like

Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork());

And its gives you more options than Background Worker

More reference: TPL

Upvotes: 1

Variant
Variant

Reputation: 17365

The best method is to use Tasks , which are a replacement for BackgroundWorker

You can see how to report progress from a Task here: http://nitoprograms.blogspot.co.il/2012/02/reporting-progress-from-async-tasks.html

Upvotes: 0

Related Questions