views:

77

answers:

3

Simple enough question, I just need to break through one minimal wall of confusion.

So based on the simple code below:

 Task task1 = new Task(() =>
            {
                for (int i = 0; i < 500; i++)
                {
                    Console.WriteLine("X");
                }
            });

        task1.Start();
        task1.Wait();

        for (int j = 0; j < 500; j++)
        {
            Console.WriteLine("Y");
        }

        Console.ReadLine();
  1. So based on the above, will the Task be on its own separate thread and the other code on the main thread?

  2. Now in terms of wait, I'm confused as to what I am instructing to wait. So going back to the above example, let's say now Task 1 has an insane amount of work to do and in the main thread only exists a single statement like below:

        Task task1 = new Task(() =>
            {
                //insane amount of work to do which might take a while
            });
        task1.Start();
        task1.Wait();
        Console.WriteLine("HI");
    
    
    
    Console.ReadLine();
    

Is the Wait just blocking the thread Task1 is on? If so, shouldn't that allow the other thread (the main thread) with the WriteLine statement to execute before task1 is complete? Or is the wait saying "No threads shall run until I am done"?

+2  A: 
  1. The task is scheduled for execution in the current TaskScheduler, which means it will run in a different thread.

  2. Wait instructs the main thread to wait until the task is completed.

qstarin
Ah alright, so Wait is always directed at the main thread. I'm assuming this means then that context switch can still occur between other tasks (if I have more than one task) on other threads right?
Ilya
Wait affects whichever thread calls it. Yes, other tasks will continue to run. Also, I see you've asked a handful of questions but have not accepted any answers. If you are not familiar with how/why to accept answers, please read http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about
qstarin
+1  A: 

task1 one will run in a seperate thread. task1.Wait() instructs the main thread to wait until task1 has finished executing.

Ben Robinson
+1  A: 

Wait cause the calling thread to wait for the Task to complete. Essentially what this code does is run synchronously across 2 threads and will take longer than if you just ran it on one thread without getting any benefits like freeing up a UI thread.

John Bowen