using System.Diagnostics 可以制作一个定时器

来源:互联网 发布:土木转金融 知乎 编辑:程序博客网 时间:2024/05/21 17:20
using System.Diagnostics 命名空间 包含了能够与系统进程 事件日志 和性能计数器进行交互的类 一般用于帮助诊断和调试应用程序 例如 Debug类用于帮组调试代码 Process类能够控制进程访问 Trace类能够跟踪代码的执行情况

Process 用于操作本地或者远程进程打访问 通过Process 可以在托管环境下很容易的操作对外部进程的启动或者停止,必须设置相应的FileName和Arguments属性 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace TestEqual
{
    class Program
    {
        static void Main(string[] args)
        {
            Process myProcess = new Process();
            myProcess.StartInfo.FileName = "iexplore.exe";
            myProcess.StartInfo.Arguments = "http://www.baidu.com";
            myProcess.Start();
        }
    }
}
Stopwatch 用于高精度检测运行时间 Start方法表示开始测量 Stop表示停止测量 Reset 表示停止测量并重置 为0最后以Elapsed返回测量时间:
using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Collections;
 using System.Diagnostics;
 namespace TestEqual
 {
     class Program
     {
         static void Main(string[] args)
         {
             ArrayList mylist = new ArrayList();
             Stopwatch watch = Stopwatch.StartNew();
             for (int i = 0; i < 100000; i++)
             {
                 mylist.Add(i);
             }
             watch.Stop();
             Console.WriteLine(watch.ElapsedMilliseconds);
             Console.ReadLine();
         }
    }
 }
EventLog 提供了写入 读取 创建 和删除事件日志的方法 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace TestEqual
{
    class Program
    {
        static void Main(string[] args)
        {
            EventLog mylog = new EventLog("MyLog", ".", "AnyLog");
            mylog.WriteEntry("It is my log.", EventLogEntryType.Information, 1);
            foreach (EventLogEntry ele in mylog.Entries)
            {
                Console.WriteLine(ele.Message);
            }
        }
    }
}
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类提供的功能了。
利用 system.diagnostics.debug 类和 system.diagnostics.trace 类可以帮助程序员方便地进行调试程序并检测程序运行情况。
debug类的所有调用仅在程序的debug版本中有效;而trace类的调用能在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纪录在日志中。
对应的wpf例子:
 


使用用条件属性的例子:
        string _lastName="";
        public string LastName
        {
            get
            {
                CheckState();
                return _lastName;
            }
            set
            {
                CheckState();
                _lastName = value;
                CheckState();
            }
        }

        //如果不是Debug模式 等同于
        //public string LastName
        //{
        // get
        // {
        // return _lastName;
        // }
        // set
        // {
        // _lastName = value;
        // }
        //}
        [Conditional("DEBUG")]
        private void CheckState()
        {
            // Grab the name of the calling routine:
            string methodName =
              new StackTrace().GetFrame(1).GetMethod().Name;

            Trace.WriteLine("Entering CheckState for Person:");
            Trace.Write("\tcalled by ");
            Trace.WriteLine(methodName);

            Debug.Assert(_lastName != null,
              methodName,
              "Last Name cannot be null");

            Debug.Assert(_lastName.Length > 0,
              methodName,
              "Last Name cannot be blank");

            Trace.WriteLine("Exiting CheckState for Person");
        }
        
        private void DebugBtn_Click(object sender, RoutedEventArgs e)
        {
            LastName = "";
        }
0 0
原创粉丝点击