码迷,mamicode.com
首页 > Windows程序 > 详细

.NET: C#: System.Diagnostics

时间:2015-07-01 17:29:34      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

1. Trace & Debug

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

技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Diagnostics;
 9 using System.Windows.Forms;
10 using System.Threading;
11 
12 namespace ControlTest
13 {
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19             Trace.Listeners.Add(new ListBoxLogTraceListener(listBox1));
20             Debug.Listeners.Add(new TextWriterTraceListener(System.IO.File.CreateText("log.txt")));
21             Debug.AutoFlush = true;
22         }
23 
24         private void Form1_Load(object sender, EventArgs e)
25         {
26             //Thread newThread = new Thread(new ThreadStart(run));
27             //newThread.Start();
28         }
29 
30         private void button1_Click(object sender, EventArgs e)
31         {
32             Debug.WriteLine(string.Format("{0}: {1}", DateTime.Now, "Debug msg..."));
33         }
34 
35         private void button2_Click(object sender, EventArgs e)
36         {
37             Trace.WriteLine(string.Format("{0}: {1}", DateTime.Now, "Trace msg..."));
38         }
39         private void run()
40         {
41             while (true)
42             {
43                 Debug.WriteLine("Debug msg...");
44                 Thread.Sleep(1000);
45                 Trace.WriteLine("Trace msg...");
46                 Thread.Sleep(1000);
47             }
48         }
49     }
50 
51     public class ListBoxLogTraceListener : DefaultTraceListener
52     {
53         private ListBox m_ListBox { get; set; }
54         public ListBoxLogTraceListener(ListBox listBox)
55         {
56             m_ListBox = listBox;
57         }
58         public override void WriteLine(string message)
59         {
60             if (!m_ListBox.Visible) return;
61             if (m_ListBox.InvokeRequired)
62             {
63                 m_ListBox.BeginInvoke(new MethodInvoker(delegate { WriteLine(message); }));
64                 return;
65             }
66             m_ListBox.Items.Add(message);
67         }
68     }
69 }
View Code

 

.NET: C#: System.Diagnostics

标签:

原文地址:http://www.cnblogs.com/yingzhongwen/p/4613347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!