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

Accessing SQLite database from Assets Folder without copying to user's data folder

android sqlite android-studio android-assets

In my iOS app I have a large (270MB), pre-populated, read-only sqlite database. I keep the data in the app bundle and query it with no problems. I do not copy the database to the user's documents

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.