并行遍历字符串列表,并在另一个列表中返回结果 [英] Loop through a list of strings in parallel, returning results in another list
问题描述
我有一个字符串列表,我需要对其执行一些操作.下面是一段很完美的代码.
I have a list of strings that I need to perform some action on. Below is a simple piece of code that works perfectly.
我想加快"ProcessList()"方法的执行,我的理解是,我可以实现一些并行处理,以便对字符串进行并行而不是串行处理.
I'd like to speed up the execution of the "ProcessList()" method and my understanding is that I could implement some parallel processing so the strings get processed in parallel rather than serially.
我已经做了一些搜索,但是对于这种并行处理的东西我还是很陌生,所以我什至不确定要搜索什么.一个简单的代码示例或指向非常相似的示例的链接将非常有帮助.
I've done some searching but I'm fairly new to this parallel processing stuff so I'm not even sure what exactly to be searching for. A simple code sample or link to a very similar example would be immensely helpful.
注意:我正在使用.NET 3.5,因此"System.Threading.Tasks"库不可用.如果可能的话,我希望可以立即使用.NET 3.5进行操作,而无需下载其他库.
Note: I'm working with .NET 3.5 so the "System.Threading.Tasks" library isn't available. If at all possible I'd like to be able to do it with .NET 3.5 out of the box without downloading additional libraries.
using System.Collections.Generic;
using System;
class Program
{
static void Main(string[] args)
{
// get a list of strings
var list = new List<string>() { "item1", "item2", "item3", "item4" };
// process the list
var resultList = ProcessList(list);
// print out the results of the list
resultList.ForEach(x => Console.WriteLine(x));
Console.ReadLine();
}
private static List<string> ProcessList(List<string> list)
{
// create list to return
var resultList = new List<string>();
// loop through each string in the list and call the "ProcessString()" method for each one
list.ForEach(x => resultList.Add(ProcessString(x)));
// return list of processed strings
return resultList;
}
private static string ProcessString(string input)
{
// do something here
return input.ToUpper();
}
}
推荐答案
您可以开始阅读一些示例来创建自己的用于处理字符串的实现:
Few examples you can start reading to create your own implementation for processing strings:
一个简单的Parallel.ForEach在.NET 3.5中实现
但是,如果可以使用外部库,那么我建议使用任务并行库是已经可以从NuGet获得
But if it is feasible to use external library then I recommend using Task Parallel Library it is already available from NuGet
Parallel.ForEach()
它提供了管理MaxDegreeOfParallelism
和Scheduler
选项的方法,如果您创建自己的实现,则必须由您自己管理.
It provides ways to manage your MaxDegreeOfParallelism
and Scheduler
options which has to be managed by yourself if you creating your own implementation.
这篇关于并行遍历字符串列表,并在另一个列表中返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!