-1

First i am sorry if there is another thread like this and i didnt saw it! My problem is: I want to create multiple threads. But these threads must execute same function. How i can make this happen? Like so :

for(int i=0;i<20;i++)
{
  Thread t = new Thread(myFunction);
  t.Start();
}

Is there any way to make this work?

svick
  • 236,525
  • 50
  • 385
  • 514

2 Answers2

0

Why not use tasks? It is also Async (since that is what you are looking for I think.

for(int i=0;i<20;i++)
{
  Task task = new Task(new Action(myFunction));
  task.Start();
}

The difference can be found here:

What is the difference between task and thread?

Community
  • 1
  • 1
Maximc
  • 1,722
  • 1
  • 23
  • 37
0

I don't see anythign wrong with what you have (maybe if you share some of the code in myFunction, we could get a better picture).

I would recommend that you either use the ThreadPool, or that you use the Task Parallel library instead of manually creating your own thread.

Here are a few techniques:

System.Threading.Tasks.Parallel.For(0, 20, myFunction); // myFunction should accept an int, and return void)

If the signature of myFunction is different, you could use a lambda to "translate" -- be aware that you are calling a function that calls a function here:

Parallel.For(0, 20, i => myFunction()); //(I could pass any param to my function in this example)

Here's a a threadpool way

System.Threading.Threadpool.QueueUserWorkItem(myFunction) // myFunction needs to accept an object

// here's how to queue it to the threadpool with any signature

ThreadPool.QueueUserWorkItem(s => myFunction());

Another poster already mentioned using Tasks to do it. If what you are doing is pretty simple, I would just use the Parallel.For.

JMarsch
  • 21,484
  • 15
  • 77
  • 125