问题
I am learning task aysny based programing and cannot get to make this code work. The console prints the message only once and then disappears.
if I remove the read line and run the program(not debug mode) the console just appears with message saying press a key to continue. When I debug and put the debugger in console.write then it works fine for some time and then the console window disappears and restarts again. If I use for loop <10000 instead of while then also the behaviors is same
Could you please suggest what I am doing wrong.
static void Main(string[] args)
{
multitasker();
}
static async void multitasker()
{
Task task1 = new Task(PrintMessageA);
task1.Start();
await task1;
}
static void PrintMessageA()
{
while(true)
{
Console.WriteLine("Message from A");
Console.ReadLine();
}
}
回答1:
Your main thread does not block and thus is exiting immediately. You would have to go "await all the way" in a sense and await multitasker
as well, but you can't actually do that as seen later.
So first you return a task in multitasker
static async Task multitasker()
{
Task task1 = new Task(PrintMessageA);
task1.Start();
await task1;
}
The problem is you cannot make Main()
(the entry point) async, so instead you would need to block that thread by instead calling Wait()
on the returned Task
static void Main(string[] args)
{
multitasker().Wait();
}
来源:https://stackoverflow.com/questions/42331050/console-writeline-within-task-does-not-work