代码之家  ›  专栏  ›  技术社区  ›  Kiril

自定义跟踪输出

  •  2
  • Kiril  · 技术社区  · 14 年前

    我在用 Trace

    第一个项目是一个控制台应用程序,我将把它转换成一个服务(此时我将消除控制台跟踪),我将添加两个 痕迹 听众:

    Trace.Listeners.Add(new TextWriterTraceListener(someFileStream));
    Trace.Listeners.Add(new ConsoleTraceListener());
    

    第二个项目是 WinForm 应用程序和我有一个“ConsoleForm”,它显示跟踪信息,用户可以随意打开和关闭它。对于该应用程序,我还添加了一个 痕迹 侦听器:

    Trace.Listeners.Add(new TextWriterTraceListener(
        new TextBoxStreamWriter(new WriteToTextBox(OnTextBoxWrite))));
    

    这个 TextBoxStreamWriter 是我创建的一个自定义类,它允许我向 ConsoleForm 没有 当windows应用程序显示任何性能跟踪时,下面是一个性能跟踪示例:

    使用率:[0%],内存使用率:59mb

    更新

    我没做什么疯狂的事,其实很简单。。。这是我的密码:

    public partial class ConsoleForm : Form
    {
        public delegate void WriteToTextBox(string value);
    
        public ConsoleForm()
        {
            InitializeComponent();
            Trace.AutoFlush = true;
            Trace.Listeners.Add(new TextWriterTraceListener(
                new TextBoxStreamWriter(new WriteToTextBox(OnTextBoxWrite))));
        }
    
        private void ConsoleForm_Load(object sender, EventArgs e)
        {
        }
    
        private void OnTextBoxWrite(string value)
        {
            if (!this.IsHandleCreated)
                return;
    
            if (this.InvokeRequired)
            {
                object[] parameters = { value };
                BeginInvoke(new WriteToTextBox(OnTextBoxWrite), parameters);
            }
            else
            {
                // ConsoleBox is a simple multiline text box
                ConsoleBox.AppendText(value);
            }
        }
    
        private void ConsoleForm_Closing(object sender, FormClosingEventArgs e)
        {
            Trace.Flush();
            if (e.CloseReason != CloseReason.FormOwnerClosing )
            {
                e.Cancel = true;
                this.Hide();
            }
        }
    }
    

    我的 TextBoxStreamWriter 实现 TextWriter 文本框流编写器 可以找到实现 here (pastie).

    2 回复  |  直到 14 年前
        1
  •  1
  •   Les    14 年前

    仅仅添加一个TraceListener不会导致该消息被记录。

        2
  •  0
  •   Kiril    14 年前

    多亏了Les,我强迫自己深入研究“问题”,并意识到第三方DLL导致了性能日志。C#或 Trace 类,该类将显示除程序员的代码或引用的库以外的任何其他位置的跟踪消息。