.NET: C#: System.Diagnostics

时间:2025-02-02 12:04:08

1. Trace & Debug

理解这两者的区别,Trace有个Listners.Add()非常好用,这里网上有个在ListBox里输出Debug和Trace信息的

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Diagnostics;
 using System.Windows.Forms;
 using System.Threading;

 namespace ControlTest
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
             Trace.Listeners.Add(new ListBoxLogTraceListener(listBox1));
             Debug.Listeners.Add(new TextWriterTraceListener(System.IO.File.CreateText("log.txt")));
             Debug.AutoFlush = true;
         }

         private void Form1_Load(object sender, EventArgs e)
         {
             //Thread newThread = new Thread(new ThreadStart(run));
             //newThread.Start();
         }

         private void button1_Click(object sender, EventArgs e)
         {
             Debug.WriteLine(string.Format("{0}: {1}", DateTime.Now, "Debug msg..."));
         }

         private void button2_Click(object sender, EventArgs e)
         {
             Trace.WriteLine(string.Format("{0}: {1}", DateTime.Now, "Trace msg..."));
         }
         private void run()
         {
             while (true)
             {
                 Debug.WriteLine("Debug msg...");
                 Thread.Sleep();
                 Trace.WriteLine("Trace msg...");
                 Thread.Sleep();
             }
         }
     }

     public class ListBoxLogTraceListener : DefaultTraceListener
     {
         private ListBox m_ListBox { get; set; }
         public ListBoxLogTraceListener(ListBox listBox)
         {
             m_ListBox = listBox;
         }
         public override void WriteLine(string message)
         {
             if (!m_ListBox.Visible) return;
             if (m_ListBox.InvokeRequired)
             {
                 m_ListBox.BeginInvoke(new MethodInvoker(delegate { WriteLine(message); }));
                 return;
             }
             m_ListBox.Items.Add(message);
         }
     }
 }