开发者

What's the difference between Console.WriteLine() vs Debug.WriteLine()?

What's the difference between Console.WriteLine() vs Deb开发者_如何转开发ug.WriteLine()?


Console.WriteLine writes to the standard output stream, either in debug or release. Debug.WriteLine writes to the trace listeners in the Listeners collection, but only when running in debug. When the application is compiled in the release configuration, the Debug elements will not be compiled into the code.

As Debug.WriteLine writes to all the trace listeners in the Listeners collection, it is possible that this could be output in more than one place (Visual Studio output window, Console, Log file, third-party application which registers a listener (I believe DebugView does this), etc.).


Console.WriteLine() is meant for console mode programs. A nice feature of Visual Studio hosting process makes its output appear in the Visual Studio Output window while debugging for processes that don't have a console. That's very useful while debugging but beware that you should remove this code (or wrap it with a #ifdef DEBUG) when you're ready to create the Release build. It will otherwise add unnecessary overhead to your program. This makes it less than ideal for debug tracing.

Debug.WriteLine() generates tracing information if you build with the DEBUG conditional #defined. Which is on by default in the Debug build. Where the output ends up can be configured in the app.exe.config file. If this config is not overridden, .NET automatically provides an instance of the DefaultTraceListener class. It sends the Debug.WriteLine() text with the Windows OutputDebugString() API function to the debugger. The Visual Studio debugger makes that appear in the Output window, just like Console.WriteLine().

A clear advantage of Debug.WriteLine() is that it generates no overhead in the Release build, the calls are effectively removed. It however does not support composite formatting, you'll need String.Format() for that. For debug tracing, the Debug class should be your choice.


If your purpose of using Console.WriteLine is solely for debugging, you better use Debug.WriteLine.

If you want to show a message to your user (In a console application), you would use Console.WriteLine.

Debug.WriteLine is only for the purpose of debugging your application. In the release mode your debug statements will be ignored.

Another usage of a console application is to test private assemblies. Rather than the traditional approach of creating some sort of GUI test harness to test the compiled version of the DLL, you can simply re-build the DLL as a console application and input/output from/to the console. I have found this technique to be faster than spending time creating a GUI test harness.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜