|
-
Jan 7th, 2009, 07:27 PM
#1
Thread Starter
New Member
[3.0/LINQ] Multi-threading in ForEach loop
I have the following code in a console app:
foreach (string str in _betterStrings)
{
doSomething(str);
}
AddRangeButNoDuplicates(_betterStrings, _goodStrings);
I would like to add multi-threading, so that there is a CommandLine parameter which specifies the maximum threads, then spawns new threads which execute the doSomething(). As each thread completes, a new thread needs to be spawned, keeping the console app running at the maximum number of threads.
If there is anyone on this board that has done this, I would greatly appreciate it if you could point me in the best direction.
Thanks in advance.
-
Jan 7th, 2009, 07:44 PM
#2
Re: [3.0/LINQ] Multi-threading in ForEach loop
I would suggest that you use the ThreadPool class to queue up your tasks and let the system worry about what's the optimum number to run simultaneously:
Code:
private static string[] _betterStrings;
static void Main(string[] args)
{
foreach (string str in _betterStrings)
{
System.Threading.ThreadPool.QueueUserWorkItem(DoSomething, str);
}
}
private static void DoSomething(object state)
{
string str = state as string;
// Use str here.
}
That will queue up an instance of DoSomething for each string in the array and each will be executed as a thread pool thread becomes available.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|