Aakash
Aakash

Reputation: 695

How to implement multi-threading and parallel execute several tasks?

I am new to threaded programming. I have to run few tasks in PARALLEL and in Background (so that main UI execution thread remain responsive to user actions) and wait for each one of them to complete before proceeding further execution.

Something like:

foreach(MyTask t in myTasks)
{
  t.DoSomethinginBackground(); // There could be n number of task, to save 
                               // processing time I wish to run each of them 
                               // in parallel
}

// Wait till all tasks complete doing something parallel in background


Console.Write("All tasks Completed. Now we can do further processing");

I understand that there could be several ways to achieve this. But I am looking for the best solution to implement in .Net 4.0 (C#).

Upvotes: 3

Views: 33419

Answers (3)

Nolonar
Nolonar

Reputation: 6122

To me it would seem like you want Parallel.ForEach

Parallel.ForEach(myTasks, t => t.DoSomethingInBackground());

Console.Write("All tasks Completed. Now we can do further processing");

You can also perform multiple tasks within a single loop

List<string> results = new List<string>(myTasks.Count);
Parallel.ForEach(myTasks, t =>
{
    string result = t.DoSomethingInBackground();
    lock (results)
    { // lock the list to avoid race conditions
        results.Add(result);
    }
});

In order for the main UI thread to remain responsive, you will want to use a BackgroundWorker and subscribe to its DoWork and RunWorkerCompleted events and then call

worker.RunWorkerAsync();
worker.RunWorkerAsync(argument); // argument is an object

Upvotes: 8

cuongle
cuongle

Reputation: 75296

You can use Task library to complete:

 string[] urls = ...;
 var tasks = urls.Select(url => Task.Factory.StartNew(() => DoSomething(url)));

To avoid locking UI Thread, you can use ContinueWhenAll in .NET 4.0:

Task.Factory.ContinueWhenAll(tasks.ToArray(), _ => 
    Console.Write("All tasks Completed. Now we can do further processing");
);

If you are in the latest version of .NET, you can use Task.WhenAll instead

Upvotes: 1

Huy Do
Huy Do

Reputation: 44

If you use Net 4.0 or up, refer to the Parallel class and Task class. Joseph Albahari wrote very clear book about that: http://www.albahari.com/threading/part5.aspx#_Creating_and_Starting_Tasks

Upvotes: 0

Related Questions