System.Diagnostics.Trace in Textbox

In manchen Applikationen wird intensiv gebrauch von Tracing gemacht. Für Debugging Zwecke kann es nun nützlich sein, die Tracing Messages, Realtime, in einer Textbox auszugeben. Das folgende Snippet zeigt wie sich der Trace in einer Texbox anzeigen lässt.

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Timers;
using GalaSoft.MvvmLight;

namespace Me.OutlookSync.UI.ViewModel
{
    public class TraceViewModel : ViewModelBase
    {
        private string traceText;
        public string TraceText
        {
            get { return traceText; }
            set { Set(ref traceText, value); }
        }

        public TraceViewModel()
        {
            var stringStreamWriter = new StringStreamWriter(t => TraceText += t);
            var listener = new TextWriterTraceListener(stringStreamWriter);
            Trace.Listeners.Add(listener);
        }

        private class StringStreamWriter : TextWriter
        {
            private readonly Timer timer = new Timer(1000);
            private readonly Action onChange;
            private readonly StringBuilder buffer = new StringBuilder();

            public StringStreamWriter(Action onChange)
            {
                this.onChange = onChange;
                timer.Elapsed += TimerOnElapsed;
            }

            private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
            {
                onChange.Invoke(buffer.ToString());
                buffer.Clear();
            }

            public override void Write(char value)
            {
                if (!timer.Enabled)
                {
                    timer.Enabled = true;
                }

                base.Write(value);
                buffer.Append(value);
            }

            public override Encoding Encoding
            {
                get { return Encoding.UTF8; }
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *