using System.Diagnostics 可以製作一個定時器

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 = "";
        }
發佈了27 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章