Results 1 to 2 of 2

Thread: [3.0/LINQ] Multi-threading in ForEach loop

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2009
    Posts
    1

    [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.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width