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

Answers


@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);

Need Your Help

Match with substring in mongodb aggregation

regex mongodb

In my mongodb collection, I have a time_stamp="2013-06-30 23:58:37 928".

Finding all messages with a given PR_SEARCH_KEY

performance email exchange-server mapi

I need to query an Exchange server to find all messages having a certain value in PR_SEARCH_KEY. Do I have to open every mailbox and iterate through it or is there a faster solution?