net核心main中的循环,或者监听方法



我被下列阻止

使用netcore/c#创建监听过程的最佳方法是什么?我正在寻找类似的方法使用监听nodejs的方法http.createServer((.listening((,//这是一个循环,在等待请求时,我需要类似的东西,但在netcore控制台中。

我试过这个:带有"while"的无限循环,但这种方式会消耗处理器,另一种方法是使用Console.ReadLine((,如下所示:

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

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

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",程序就不会等待,运行并完成

最新更新