解决 Rider Debug Console 窗口不显示 Console.Write/WriteLine 的输出

自从使用 Rider 后,基本上就没有用过 VS 了。虽然这不是什么大问题,但真的很烦人。

这是 Rider 的一个 bug,虽然通过 Debug.Write/WriteLine 是可以在 Debug Output 窗口输出的。但是对于第三方的代码,你不可能因为 Rider 而去重写他人的代码,因为团队开发中,其他成员可能用的是 VS,VS 是没有这个问题。

解决方法

这个 bug 可以在这里 No Console.Write/Writeline Output in an Application compiled with Windows subsystem : RIDER-15637 找到,距今已经 5 年了,还未修复,看来 JetBrains 对 Rider 也是不够重视啊。

在该页面中也有人给出了解决方法,该代码的作用是将当前进程的控制台输出重定向到父进程。具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private const int ATTACH_PARENT_PROCESS = -1;

[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);

/// <summary>
/// Redirects the console output of the current process to the parent process.
/// </summary>
/// <remarks>
/// Must be called before calls to <see cref="Console.WriteLine()" />.
/// </remarks>
public static void AttachToParentConsole()
{
AttachConsole(ATTACH_PARENT_PROCESS);
}

希望 Rider 尽快修复这个 bug 吧。

Console.WriteLine() 与 Debug.WriteLine() 之间有什么区别?

Console.WriteLine()

Console.WriteLine 在调试或发布中写入标准输出流。

Console.WriteLine() 用于控制台模式程序。Visual Studio 托管进程的一个很好的功能是在调试没有控制台的进程时,它的输出显示在 Visual Studio 输出窗口中。这在调试时非常有用,但请注意,当您准备好创建发布版本时,您应该删除此代码(或用 #ifdef DEBUG 包装它)。否则会给您的程序增加不必要的开销。这使得它不太适合调试跟踪。

Debug.WriteLine()

Debug.WriteLine写入Listeners集合中的跟踪侦听器,但仅当在调试中运行时。当应用程序在发布配置中编译时,Debug 元素不会被编译到代码中。

Debug.WriteLine()如果您使用 DEBUG 条件 #defined 进行构建,则会生成跟踪信息。默认情况下在调试版本中启用。可以在 app.exe.config 文件中配置输出结束的位置。如果未覆盖此配置,.NET 会自动提供 DefaultTraceListener 类的实例。它使用 Windows OutputDebugString() API 函数将 Debug.WriteLine() 文本发送到调试器。Visual Studio 调试器使它出现在输出窗口中,就像 Console.WriteLine() 一样。

Debug.WriteLine() 的一个明显优势是它不会在 Release 构建中产生开销,调用被有效删除。但是它不支持复合格式,为此您需要 String.Format() 。对于调试跟踪,Debug 类应该是您的选择。

总结

如果您使用 Console.WriteLine 的目的仅仅是为了调试,您最好使用Debug.WriteLine

如果您想向用户显示一条消息(在控制台应用程序中),您可以使用Console.WriteLine

Debug.WriteLine 仅用于调试您的应用程序。在发布模式下,您的调试语句将被忽略。

解决 Rider Debug Console 窗口不显示 Console.Write/WriteLine 的输出

https://ganzhixiong.com/p/299c4a84/

Author

干志雄

Posted on

2023-04-02

Updated on

2023-04-02

Licensed under

Comments