如何实现多线程并并行执行几个任务? [英] How to implement multi-threading and parallel execute several tasks?

查看:511
本文介绍了如何实现多线程并并行执行几个任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是线程编程的新手.我必须在PARALLEL和后台运行一些任务(以便主UI执行线程保持对用户操作的响应),并等待它们中的每一个都完成,然后再继续执行.

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.

类似:

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");

我知道可以有多种方法来实现这一目标.但是我正在寻找在.Net 4.0(C#)中实现的最佳解决方案.

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

推荐答案

在我看来,您似乎想要

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);
    }
});

为了使主UI线程保持响应状态,您将需要使用 BackgroundWorker 并订阅其 事件,然后调用

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

这篇关于如何实现多线程并并行执行几个任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆