循环

问题描述 投票:0回答:1

我堵住了跟。

用netcorec#创建一个监听进程的最好方法是什么,我正在寻找类似于nodejs上的http.createServer().listening()的方法,/这是一个循环,等待一个请求,我需要类似的东西,但在netcore控制台。

我试过用 "while "无限循环,但这种方式会消耗处理器,另一种方式是用Console.ReadLine()这样。

ConsoleKeyInfo keyInfo = Console.ReadKey();
while (keyInfo.Key == ConsoleKey.Enter)
keyInfo = Console.ReadKey();
c# .net-core console-application
1个回答
0
投票

我们假设我有一个Main.cs文件,里面有Main方法,然后我写了一个异步的函数。

static void Main(string[] args)
        {


            Task.Run(async () => {
                await AsyncMain();
            } );

            ConsoleKeyInfo keyInfo = Console.ReadKey();
            while (keyInfo.Key == ConsoleKey.Enter)
                keyInfo = Console.ReadKey();
        }

        static async Task<int> AsyncMain()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(2000);

                Console.WriteLine(i);
            }

            return 0;
        }

例如在AsyncMain方法中(这只是个例子,并不是真正的代码),也许我可以执行一个与其他事情有反应的过程,但如果我不写 "while",程序就不会等待、运行和完成。

© www.soinside.com 2019 - 2024. All rights reserved.