Task中的console.writeline不起作用 [英] console.writeline within Task does not work

查看:243
本文介绍了Task中的console.writeline不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习基于aysny的任务编程,无法使此代码正常工作.控制台仅将消息打印一次,然后消失.

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.

如果我删除读取的行并运行程序(不是调试模式),则控制台仅显示一条消息,提示您按一个键继续.当我调试并将调试器放入console.write时,它可以正常工作一段时间,然后控制台窗口消失并再次重新启动.如果我使用< 10000而不是while循环,那么行为也是相同的

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();

            }
        }

推荐答案

您的主线程未阻塞,因此将立即退出.从某种意义上说,您将必须一直等待",也要等待multitasker,但是您实际上无法做到这一点,稍后再见.

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.

所以首先您要在multitasker

static async Task multitasker()
{
    Task task1 = new Task(PrintMessageA);
    task1.Start();
    await task1;            
}

问题是您无法使Main()(入口点)异步,因此您需要通过在返回的Task上调用Wait()来阻塞该线程

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();
}

这篇关于Task中的console.writeline不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆