How to implement multi-threading and parallel exec

2019-02-15 09:41发布

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#).

4条回答
再贱就再见
2楼-- · 2019-02-15 10:10

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

查看更多
We Are One
3楼-- · 2019-02-15 10:14
一纸荒年 Trace。
4楼-- · 2019-02-15 10:18

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
查看更多
时光不老,我们不散
5楼-- · 2019-02-15 10:30

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

查看更多
登录 后发表回答