Simsons
Simsons

Reputation: 12745

Why Task does not start without Wait

When I create a Task :

for (int i = 0; i < 5; i++)
{
   // var testClient =
        Task.Factory.StartNew(
        () =>
        {
            TaskClient();
        }); 
}  

public static void TaskClient()
{
    System.Console.WriteLine("--------------------");
}

But this does not start the Console Write Untill I wait for the task!!!

Task.Factory.StartNew(
            () =>
            {
                TaskClient();
            }).Wait();

Why do we need to call Wait , When I am already starting the thread using StartNew

Upvotes: 0

Views: 957

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

@vcsjones has to be right. You don't see the result because program ended and window was closed.

I've tried your code and if I run the program from cmd, without debugger I can see the correct output. To make it a little more meaningful I've added another Console.WriteLine at the end of Main method:

for (int i = 0; i < 5; i++)
{
    // var testClient =
    Task.Factory.StartNew(
    () =>
    {
        TaskClient();
    });
}

Console.WriteLine("End of program execution.");

Returns:

End of program execution.
--------------------
--------------------
--------------------
--------------------
--------------------

As you can see, it works just fine.

If you want to wait with further execution untill all tasks are done, you can use Task.WaitAll static method:

var tasks = new Task[5];

for (int i = 0; i < 5; i++)
{
    // var testClient =
    tasks[i] = Task.Factory.StartNew(
                () =>
                {
                    TaskClient();
                });
}

Task.WaitAll(tasks);

Upvotes: 1

Related Questions