Home > OS >  After Task starts, it displays only if calling another method
After Task starts, it displays only if calling another method

Time:11-21

void Something() => System.Console.WriteLine("Something is done");
Task t = new Task(delegate {Something();});
t.Start();  // nothing activates unless the below code is uncommented
// System.Console.WriteLine(33);  //displays "33 \nSomething is done" as long as not commented out

I don't understand something fundamental about Task. In the code above, if line 4 is commented out, nothing is written on the console, but if you write in System.Console.WriteLine(33), then the number 33 displays AND "Something is done" displays.

  1. I don't understand why t.Start() doesn't write "Something is done".
  2. Why does writing anything after t.Start(), activate it?

Thank you.


Update: This is my whole program. It is intended to understand the behavior of Task, so the program is small.

CodePudding user response:

The main thread does not block and hence is exiting immediately without Console.WriteLine. Console.WriteLine is done on the main thread.

Since this is a console app, the call to the Wait method is necessary to prevent the app from terminating before the task finishes execution.

t.Start();
t.Wait();  

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.start?view=net-7.0#system-threading-tasks-task-start

Another way is to make the Main method async.

public static async Task Main()
{
    Task t = new Task(delegate { Something(); });
    t.Start();
    await t;
}
  • Related