Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Article

A Simple TextBox TraceListener

Rate me:
Please Sign up or sign in to vote.
4.98/5 (21 votes)
24 Oct 2007MIT2 min read 89.2K   2.4K   36   15
A tracelistener class that allows you to view the results of the trace in your Windows UI test harness
Screenshot - TextBoxTraceListener.jpg

Introduction

This is a simple custom TraceListener class to allow text boxes to show the result of the trace in a multi-threaded application.

Background

I was writing a test harness for one of my services and figured someone would have already published a TextBoxTraceListener class to save me five minutes, but unfortunately Google came up short. The only examples I could see weren't threadsafe and would have needed all the code to be executed on the Windows UI thread - not exactly great when you're running a service test harness. So I figured I'd throw one together and put it out there for re-use. It's a very simple class really just to save people a bit of time.

Using the Code

Just add the TextBoxTraceListener class to your code, then create an instance of the listener (passing in the textbox you want to output the trace to in the constructor), then add your trace listener to Trace or Debug. The sample test harness should give you a pretty good idea of what to do, but it's probably going to look something like this (where txtDisplayTrace is a text box on the form):

C#
public partial class Form1 : Form
{
    TextBoxTraceListener _textBoxListener;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _textBoxListener = new TextBoxTraceListener(txtDisplayTrace);
        Trace.Listeners.Add(_textBoxListener);
    }
}

Points of Interest

I very rarely get to do anything that requires a UI, so I frequently forget that you can't access controls from a different thread until I compile and get an error (then the memory of previous pains comes flooding back). Of course to solve this issue, all you have to do is call Invoke on the control in question and pass it a delegate to the method you want to execute, which is pretty much all that the TextBoxTraceListener does; extend the TraceListener class and invoke the update method (the code file has comments, which I've stripped from here).

C#
public class TextBoxTraceListener : TraceListener
{
    private TextBox _target;
    private StringSendDelegate _invokeWrite;

    public TextBoxTraceListener(TextBox target)
    {
        _target = target;
        _invokeWrite = new StringSendDelegate(SendString);
    }
    
    public override void Write(string message)
    {
        _target.Invoke(_invokeWrite, new object[] { message });
    }

    public override void WriteLine(string message)
    {
        _target.Invoke(_invokeWrite, new object[] 
            { message + Environment.NewLine });
    }

    private delegate void StringSendDelegate(string message);
    private void SendString(string message)
    {
        // No need to lock text box as this function will only 
        // ever be executed from the UI thread
        _target.Text += message;
    }
}

Hopefully someone out there will find it useful for saving five minutes of coding.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Web Developer
England England
Adam lives in York and is just starting a new job as a senior web developer for a major travel company in the UK. He holds an MCPD for Web Development in ASP.NET 2 and has an interest in further developing his AJAX skills in the near future and will be practicing by developing his own site: Solid Code

Comments and Discussions

 
QuestionGreat!! Pin
Jan Navarro11-Jun-14 1:10
Jan Navarro11-Jun-14 1:10 
GeneralThanks for the complete solution Pin
Volodymyr tvv Tkachenko29-Oct-09 4:39
Volodymyr tvv Tkachenko29-Oct-09 4:39 
Generalmy 2 cents Pin
SPENNER23-Oct-09 5:51
SPENNER23-Oct-09 5:51 
General5 minutes [modified] Pin
BigTimeDonkey12-Oct-08 14:37
BigTimeDonkey12-Oct-08 14:37 
QuestionThreadsave? Pin
wotina31-Mar-08 3:28
wotina31-Mar-08 3:28 
Generalscroll to end Pin
canozurdo1-Nov-07 3:43
canozurdo1-Nov-07 3:43 
GeneralRe: scroll to end Pin
Adam Crawford1-Nov-07 15:15
Adam Crawford1-Nov-07 15:15 
GeneralRe: scroll to end Pin
Intarwebmaster14-Nov-07 4:25
Intarwebmaster14-Nov-07 4:25 
GeneralRe: scroll to end Pin
Adam Crawford14-Nov-07 22:18
Adam Crawford14-Nov-07 22:18 
GeneralNewbi question from an old timer Pin
redWingBB31-Oct-07 6:56
redWingBB31-Oct-07 6:56 
GeneralRe: Newbi question from an old timer Pin
fwd31-Oct-07 22:24
fwd31-Oct-07 22:24 
Generalhave you heard about.... Pin
Ollie26-Oct-07 5:09
Ollie26-Oct-07 5:09 
GeneralRe: have you heard about.... Pin
Adam Crawford26-Oct-07 5:25
Adam Crawford26-Oct-07 5:25 
GeneralRe: have you heard about.... Pin
Ollie27-Oct-07 0:25
Ollie27-Oct-07 0:25 
GeneralRe: have you heard about.... Pin
Adam Crawford27-Oct-07 1:07
Adam Crawford27-Oct-07 1:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.