0

I am trying to learn C# multithreading. This question might be stupid for some but anyways I will still ask it.

Question:

I'm trying to figure out where should I put (if I'm asking the right question) the thread.wait() method. So it could show all the child threads in the console. This is the output that I would like to have.

The int num that I inputted is 3.

This should be the output (I am running this with breakpoint):

enter image description here

This is the current output:

enter image description here

Here is my Code:

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Input number of threads: ");
            int num = Convert.ToInt32(Console.ReadLine());

            Task[] TaskArray = new Task[num];

            for (int i = 0; i <= num-1; i++)
            {
                TaskArray[i] = Task.Run(() => { DifferentMethod(i); });                
            }

            for (int i = 0; i <= num - 1; i++)
            {
                TaskArray[i].Wait();
            }
        }
        static void DifferentMethod(object ThreadID)
        {
            while (true)
            {
                Console.WriteLine("{0} is Running",ThreadID);                 
                Thread.Sleep(500);
            }
        }
    }
}
k9nneo1191
  • 97
  • 8
  • 7
    Tasks != Threads. – Daniel A. White Nov 01 '17 at 12:28
  • `Task.Run` == Threads – Bradley Uffner Nov 01 '17 at 12:45
  • 1
    @BradleyUffner no. Do you suppose that if I create 1 million tasks with `Task.Run` there would be 1 million threads executing them? – Sergey.quixoticaxis.Ivanov Nov 01 '17 at 12:57
  • No, of course not. Calling `Task.Run` does guarantee that user code will be running in multiple threads though. As far as I understand it, and please correct me if I'm wrong, calling `Task.Run` will always run code in a thread different than the one that called it. I don't see any way that could *not* be considered "multi-threading". – Bradley Uffner Nov 01 '17 at 13:12
  • @BradleyUffner That's false. `Task.Run` schedules work to be done in a thread pool thread. That may or may not be a different thread. If the current thread isn't a thread pool thread *then* you can say that it'll run in a different thread. In fact, when scheduling work from a thread pool thread it's *more* likely to run in the current thread then another thread in many situations. – Servy Nov 01 '17 at 15:17
  • @Servy that's good to know, thank you. But I'm still sticking with my statement that calling `Task.Run` inherently means dealing with multi-threading at some level, even if it is just a lowly thread-pool thread. – Bradley Uffner Nov 01 '17 at 15:29
  • @BradleyUffner Sure, that, unlike any of your previous statements, is correct. Calling `Task.Run` does inherently mean dealing with multi-threading at some level. – Servy Nov 01 '17 at 15:30

2 Answers2

5

This has nothing to do with your waiting part.

You need to make a local copy of your variable:

for (int i = 0; i <= num-1; i++)
{
   int localCopy = i;
   TaskArray[i] = Task.Run(() => { DifferentMethod(localCopy); });                
}

Because your i is "captured" (for lack of a better word) but it has already changed by then. So you make a local copy so the capture is on the local copy, that never changes.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Thx for the help.. it works.. – k9nneo1191 Nov 01 '17 at 12:50
  • 1
    @k9nneo1191 also note that (if I understand your code correctly) you wait only for the `TaskArray[0]` and wait for it forever because it will never be completed. – Sergey.quixoticaxis.Ivanov Nov 01 '17 at 12:58
  • oh. i thought if a made a for loop that the main thread will just create the child threads and go on its way. And the child thread goes to the methods while loop and never be completed. thx for the additional knowledge. – k9nneo1191 Nov 01 '17 at 13:19
0

You could use the static method from the Task class Task.WaitAll(TaskArray) and the main thread will wait at that point for all tasks to finish

Ivelin Ivanov
  • 148
  • 3
  • 14