随着我们程序的逐渐庞大,业务逻辑的逐渐复杂,我们写的代码往往,或者说越来越不按照我们预料的方式运行。碰到这样的情况,通常我们会使用Debugger来调试我们的程序。但是,Debugger不是万能的。我们程序里会有总多的线程,会有很多的循环,这样情况下,会使调试变的非常麻烦,我们也会很头疼。
于是,通过使用Trace或Debug,我们会将程序的状态输出到消息记录(EvengLog)上来,通过查看消息记录,我们便多了一条解决问题的路径,从而使的我们的程序更加的Robust!
1.NameSpace
System.Diagnostics
2.简介
这两个类都提供了一些方法,通过使用这些方法,你可以输出一些程序的状态,抛出一个错误之类的。
两者不同的地方,Trace可以在程序运行的时候使用,而Debug只能在调试的时候使用。就是说,通过调用Trace的方法输出消息,在程序运行的时候仍然可以捕获到这些消息。而Debug输出的消息,只有在调试的时候才能够看到。
3.Trace类定义
不直接写了,直接看定义。
这里也不翻译了,英文也比较简单易懂。

Method

Description

Assert (condition, message)

Displays the specified string message when the condition provided to the method evaluates to false. When you do not specify the message text, the Call Stack is displayed instead.

Fail (message)

Similar to the Assert() method, this writes the specified text to the Call Stack when a failure occurs. The Assert() method differs because Fail() cannot specify a condition before displaying the error. In fact, the Fail() method is usually placed in the catch statement of a try-catch-finally instruction. You could also place it anywhere in your code that you are sure could never be reached - such as in the default case of a switch statement where you believe you've allowed for all possibilities.

Write (message | object)

Writes the specified text message, or object name, to the listener application.

WriteIf (condition, message)

Writes the specified message text into the listener application if the specified condition is true.

WriteLine (message | object)

Writes the specified message text, or object name, followed by a carriage return.

WriteLineIf (condition, message)

Writes the specified message text followed by a carriage return if the specified condition is true.

4.如何消除Trace和Debug
当你的程序想要发布的时候,你无须亲自手动将这些Trace,Debug的调用语句删掉。通过下图的配置,编译器会自动的将这些调用语句删除。



5. 如何使用Trace/Debug
使用这两个类很简单。
首先,这两个类提供了Static方法,这就意味着你无须自己去创建instance。
 1 static void Main()
 2    {
 3      Trace.WriteLine("Entered Main()");
 4 
 5      for (int i = 0; i < 6; i++)
 6        Trace.WriteLine(i);
 7 
 8      Trace.WriteLine("Exiting from Main()");
 9    }
10 
编译这样的程序,通过Visual Studio的Output窗口,你就能够看到:


posted on 2008-06-17 22:20  xiaxi  阅读(1540)  评论(0)    收藏  举报