console.writeline within Task does not work

天大地大妈咪最大 提交于 2019-12-11 10:16:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!