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.
- I don't understand why
t.Start()
doesn't write"Something is done"
. - 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();
Another way is to make the Main method async.
public static async Task Main()
{
Task t = new Task(delegate { Something(); });
t.Start();
await t;
}