如果 UseWPF/UseWindowsForms 设置为 true,C# 程序将立即退出

C# program exits immediately if UseWPF/UseWindowsForms set to true

程序:

Public Class QueryExecutor
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter y");
        if (Console.ReadLine() == "y") return;
    }
}

旧的.csproj。这会导致程序在控制台 window.

中正确请求输入
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

新的 .csproj。这会导致程序在不打开控制台的情况下退出。

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
    <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

新 .csproj 的输出:

'TFSHygiene.exe' (CoreCLR: DefaultDomain): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.0.9\System.Private.CoreLib.dll'. 
'TFSHygiene.exe' (CoreCLR: clrhost): Loaded 'C:\Users\Nathan_Dehnel\source\repos\TFSHygiene\bin\Debug\net5.0-windows\TFSHygiene.dll'. Symbols loaded.
'TFSHygiene.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.0.9\System.Runtime.dll'. 
'TFSHygiene.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.0.9\System.Console.dll'. 
'TFSHygiene.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.0.9\System.Threading.dll'. 
'TFSHygiene.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App.0.9\System.Text.Encoding.Extensions.dll'. 
The program '[31740] TFSHygiene.exe' has exited with code 0 (0x0).

.NET 5 中的重大更改。

MS Docs:

OutputType is automatically set to WinExe for Windows Presentation Foundation (WPF) and Windows Forms apps. When OutputType is set to WinExe, a console window doesn't open when the app is executed.

(...)

Recommended action

No action is required in your part. However, if you want to revert to the old behavior, set the DisableWinExeOutputInference property to true in your project file.

<DisableWinExeOutputInference>true</DisableWinExeOutputInference>

您的应用正在退出,因为 ReadLine() 上没有可用的标准输入。