-1

Main

foreach(Thread t in createTestThreads(8)) {
                t.Start();
            }
private static Thread[] createTestThreads(int ThreadCount) {
            Thread[] threads = new Thread[ThreadCount];
            for(int i = 0; i < ThreadCount; i++) {
                Thread t = new Thread(() => {
                    Console.Write(i);
                });
                threads[i] = t;
            }
            return threads;
        }

Wished Result: 01234567 (Probably not in that exact order, but doesn't have to be) Actual Result: 88888888 Is there any other way of doing this without naming the Threads manually t0, t1, t2, etc.. Like is there a way to create Threads with dynamical names for example Thread ("t" + i) = new Thread (() =>

3
  • Does Parallel list a solution for you? Commented Sep 22, 2019 at 19:57
  • 3
    The result you get is caused by the fact that lambda in C# captures a variable, not a value. What is your actual question, what are you trying to achieve? Commented Sep 22, 2019 at 19:58
  • 1
    The dupe question is a bit long but the answer applies here directly. Commented Sep 22, 2019 at 20:10

2 Answers 2

0

i is captured in your lambda; you need to copy it to a temporary variable:

for(int i = 0; i < ThreadCount; i++)
{
    int ii = i; // copy value of i to temp variable
    Thread t = new Thread(() => 
    { 
        Console.Write(ii); }); 
        threads[ii] = t;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Since this is a new contributor, I think getting him to describe his objectives clearly so he can receive and appropriate support would be better than providing a suitable answer based on his question. why is he trying to create so much thread that could be catastrophic?
@codein, agreed, and will follow your advice in the future (as this post has been closed as a duplicate anyhow). Thank you!
-1

One solution is to create one child thread to the main thread. The main thread calls the sub-class createTestThreads and send argument

createTestThreads(8)

The class initialize a thread

    Thread threads = new Thread(()=> job(8));
    threads.Start(); 

A method in the class called job

Public void job(int limit)
{
        private void job(int ThreadCount)
        {
            for(int i= 0; i < ThreadCount; i++)
            {
                Console.WriteLine(i);
            }
        } 
}

This however only initialize one child thread, are you interested in initializing 8 child threads?

1 Comment

Your code won't compile.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.