Ilya
Ilya

Reputation: 1223

C# Wait and multithreading

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"?

Upvotes: 0

Views: 361

Answers (3)

John Bowen
John Bowen

Reputation: 24453

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.

Upvotes: 1

Coding Flow
Coding Flow

Reputation: 21881

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

Upvotes: 1

quentin-starin
quentin-starin

Reputation: 26628

  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.

Upvotes: 2

Related Questions