I have a list of strings that I need to perform some action on. Below is a simple piece of code that works perfectly.
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.
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:
A Simple Parallel.ForEach Implementation in .NET 3.5
Parallel ForEach Loops in C# 3.5
Optimized Parallel ForEach .NET 3.5
But if it is feasible to use external library then I recommend using Task Parallel Library it is already available from NuGet
It provides ways to manage your
MaxDegreeOfParallelism
andScheduler
options which has to be managed by yourself if you creating your own implementation.