0

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

2
  • 1
    What happens after the loop? Does the program end? Commented Nov 19, 2013 at 18:21
  • 5
    The program is probably ending. The "wait" allows the tasks to finish (writing to the console) before the program exits. The task is starting, you're just not waiting for it to do anything without the wait. Commented Nov 19, 2013 at 18:21

1 Answer 1

1

@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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.