C# Consle.ReadLine容易忽视的坑

在微软官方CSDN Console.ReadLine的返回值说明如下

The next line of characters from the input stream, or null if no more lines are available.

具体Console.ReadLine是干什么的不做说明,这个第一天学c#的应该都知道,后半翻译成人话:当命令行不可用时返回null。
在实际的测试中,例如windows服务和linux systemd守护进程方式运行程序,如果你的代码中用了Console.ReadLine,则此处不会阻塞,而是直接返回null,从而可能会导致预期外的bug。
因此当你使用Console.ReadLine的时候务必要进行非空的判断。而且如果使用Console.ReadLine进行阻塞线程实现程序不退出时也要注意你的程序是否会在没有命令行输入的环境下运行。

posted @ 2021-10-31 21:39  gui.h  阅读(730)  评论(0编辑  收藏  举报