Spawning threads in a loop, how to ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi ! I need to spawn several threads in a loop. The exact number is a user
defined
parameter.

for(int i = 0; I < NUMBER_OF THREADS; i++)
{
// Spawn a new thread that does something
}

I am having a hard time figuring it out. I know how to use ThreadStart but
I do not know how to call it in a loop.

Any ideas, suggestions, samples, url’s are greatly appreciated.

Thank you in advance,

--Michael
 
Hi Mike,
something like the following will work:

class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(DoSomething));
t.Start();
}

}

static void DoSomething()
{
}
}

Obviously you do not want to create too many threads in your loop :-)


Hope that helps
Mark R Dawson
http://www.markdawson.org
 
class ThreadList : CollectionBase
{
public void Add(Thread t)
{
this.List.Add(t);
}
}

void SpawnThreads(int n)
{
for (int i = 0; i < n; i++)
{
SpawnThread(new ThreadStart(Method));
}
}

void SpawnThread(ThreadStart s)
{
Thread t = new Thread(s)
t.Start();
this.threads.Add(t);
}

void Method()
{
Console.WriteLine("This is running on thread " +
Thread.CurrentThread.Name);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top