System.Diagnostics.Debug和System.Diagnostics.Trace

在 .net 类库中有一个 system.diagnostics 命名空间,该命名空间提供了一些与系统进程、事件日志、和性能计数器进行交互的类库。当中包括了两个对开发人员而言十分有用的类——debug类和 trace类。本文介绍了这两个类的一些基本用途,旨在提高广大开发人员的开发效率。 
使用debug类来帮助调试

调试程序对每个程序员来说是家常便饭。可是我们会经常遇到一些情况让我们头疼,例如:

当我们在开发一个界面控件的时候,简单的设断点会增加paint事件的响应次数,而造成的环境参数改变。 
断点设多了,程序常常停在正常运行的地方;这样一来,调试一个错误要花费大量时间去寻找错误。 

时,我们就需要利用system.diagnostics.debug类来帮助我们调试。我们可以通过调用debug.writeline(string
message)函数,将我们所关心的信息打印在visual studio
ide的output窗口中。也可以利用debug.assert(bool condition)来让程序停在错误的地方,并且显示call
stack。

debug类中所有函数的调用都不会在release版本里有效。也就是说,我们通过这种方法所加的代码可以仅用于调试;在发布的时候无需删任何代码,就可以给用户一个没有调试指令的程序了。

下面的这个例子演示了这两个函数来帮助调试的方法:

1、 新建一个visual studio c# project,采用默认的项目名。

2、 往form1上拖一个label,并采用其缺省id。

3、 在form1.cs中的form1类中添加下面的函数代码:

private int time=0;
protected override void onpaint(painteventargs e)
{
time++;
this.label1.text="onpain called "+time.tostring()+" times.";
} 

protected override void onresize(eventargs e)
{
system.diagnostics.debug.assert(this.width>200,"width should be larger than 200.");
system.diagnostics.debug.writeline(size.tostring());
} 

4、 编译并运行项目的debug版本。

5、 切换visual studio .net ide到output窗口。

6、
切换到刚才的程序,改变主窗口的大小,您可以在ide中看到form1窗口的实时大小,并在form1上看到onpaint被调用的次数。当窗口的宽度小
于等于200个像素的时候,系统会弹出一个assertion fail的对话框。里面显示了当前程序的call
stack。如果您在onpaint中设置了断点,想要调试程序的话,那么您会进入一个死循环,直到您停止调试。

debug类和trace类的区别

您一定发现了在system.diagnostics命名空间中还有一个名为trace的类。它的函数功能和debug非常相似。为什么要有这样两个功能类似的类呢?


因是这样的,debug类里所提供的函数仅在编译时带#debug宏参数才奏效,一旦到了release版本中,这些函数都会被忽略。也就是说debug
类的功能仅在程序员开发的时候能用。而trace则不同,它能在release版本的程序中也被运行,这样程序员就可以在release版本的程序中添加
一些debug类提供的功能了。

使用trace类来做程序日志

接下来的问题就是:我们程序员能利用trace类的功能做些什么呢?我们可以用它来做程序的日志。

1、 打开刚刚的project。

2、 用下面的代码覆盖刚才第2步的代码:

private void calculate()
{
  int a=1,b=1;
  try
  {
    system.random r = new random();
    while (true)
    {
      a=(int)(r.nextdouble()*10);
      b=(int)(r.nextdouble()*10);
      system.diagnostics.trace.writeline(system.datetime.now.tostring()+": "+
      a.tostring()+"/"+b.tostring()+"="+(a/b).tostring());
    }
  }
  catch (exception ex)
  {
    system.diagnostics.trace.writeline(system.datetime.now.tostring()+": "+a.tostring()+
    "/"+b.tostring()+"="+" error: "+ex.message);
    messagebox.show(ex.message);
  }
} 

3、在构造函数form1()的最后添加下面的代码,将trace的输出重定向到app.log文件中:

system.diagnostics.trace.listeners.clear(); 
system.diagnostics.trace.autoflush=true; 
system.diagnostics.trace.listeners.add(new system.diagnostics.textwritertracelistener("app.log"));

4、拖一个按钮到该form上,双击按钮,在button1_click函数中添加如下代码:

calculate(); 
application.exit();

5、运行该程序的release版本,点击添加的按钮,程序便开始执行一位随机数除法。由于是随机数,可能会出现出数为0的情况,这样程序就会抛出exception,这是程序会自动中止。

6、在该程序所在的目录里您可以发现出现了一个新的文件app.log,里面记录了各个时刻的运算纪录,并把exception纪录在日志中。

小结

利用 system.diagnostics.debug 类和 system.diagnostics.trace 类可以帮助程序员方便地进行调试程序并检测程序运行情况。

debug类的所有调用仅在程序的debug版本中有效;而trace类的调用能在release版本和debug版本中都有效。

时间: 2024-07-29 20:07:54

System.Diagnostics.Debug和System.Diagnostics.Trace的相关文章

System.Diagnostics.Debug.WriteLine 在OutPut中无输出

TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out); Debug.Listeners.Add(writer); System.Diagnostics.Debug.WriteLine("-------------------");

(C# Debug)A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll

Debug 模式下运行程序的时候,Output 窗口出来个错误“A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll”. 但是并没有直接throw错误.无法知道具体在哪一步发生了这个错误. 如果想知道具体的内容,需要enable 这个debug If you do want to know, in Visual Studio -> Debug (main menu) ->

Unable to cast object of type 'System.Int32' to type 'System.String'.

最近在研究.netcore,尝试把前后端完全分离.但是在写接口的时候,Post参数是FromBody的时候报错了 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidCastException: Unable to cast object of type

C# 计时器用法(DispatcherTimer、System.Timers.Timer、System.Threading.Timer)

首先,我觉得三种计时器最大的区别是:DispatcherTimer触发的内容会直接转到主线程去执行(耗时操作会卡住主线程),另外两个则是在副线程执行,如果需要修改界面,则需要手动转到主线程. DispatcherTimer: DispatcherTimer _timer; public void TestDispatcherTimer() { _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(1); _t

System.out.println与System.err.println的区别

public class Test2 { static { System.out.println("1"); } { System.out.println("2"); } public Test2() { System.out.println("3"); System.err.println("3"); } public static void main(String[] args) { new Test2(); } } Sy

vs2013c#测试using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1_CXY { class Program { stati

首先安装Unit Test Generator.方法为:工具->扩展和更新->联机->搜索“图标为装有蓝色液体的小试管.Unit Test Generator”, 编写代码,生成一个新的类,编写构造函数 与 add()函数.代码如下. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Co

错误描述:请求“System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”类型的权限已失败

错误描述:请求“System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”类型的权限已失败. 解决办法:在配置文件web.config中<trust></trust>节点,把<trust level="WSS_Minimal" originUrl=""

System.Windows.Forms.Timer、System.Timers.Timer、System.Threading.Timer的差别和分别什么时候用

一.System.Windows.Forms.Timer 1.基于Windows消息循环,用事件方式触发,在界面线程执行:是使用得比较多的Timer,Timer Start之后定时(按设定的Interval)调用挂接在Tick事件上的EvnetHandler.在这种Timer的EventHandler中可 以直接获取和修改UI元素而不会出现问题--因为这种Timer实际上就是在UI线程自身上进行调用的. 2.它是一个基于Form的计时器3.创建之后,你可以使用Interval设置Tick之间的跨

fastboot 刷system.img 提示 sending &#39;system&#39; (*KB)... FAILED (remote: data too large)

华为G6-C00卡刷提示OEMSBL错误,只能线刷 ,但是官方找不到线刷img镜像,无奈 网上下了个可以线刷的工具套件 流氓ROM . 使用HuaweiUpdateExtractor(工具百度)把官方 UPDATA.APP 中三个镜像文件全部提取出来 尝试使用 下面命令 fastboot flash boot boot.img fastboot flash recovery recovery.img fastboot flash system system.img 最后一步出错 提示 sendi