1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
    public class TextBoxStreamWriter : TextWriter
    {
        private ConsoleForm.WriteToTextBox _output;
        private ManualResetEvent _ready;
        private Queue<String> _buffer;
        private Thread _writeService;
        private static object _sync = new object();

        public TextBoxStreamWriter(ConsoleForm.WriteToTextBox output)
        {
            lock (_sync)
            {
                _output = output;
                _buffer = new Queue<String>();
                _ready = new ManualResetEvent(false);
                _writeService = new Thread(Run);
                _writeService.IsBackground = true;
                _writeService.Start();
            }
        }

        public override void WriteLine(string value)
        {
            lock (_sync)
            {
                _buffer.Enqueue(value + "\n");
                _ready.Set();
            }
        }

        public override void Write(String value)
        {
            lock (_sync)
            {
                _buffer.Enqueue(value);
                _ready.Set();
            }
        }

        private void Run()
        {
            String value;
            try
            {
                while (true)
                {
                    _ready.WaitOne();
                    lock (_sync)
                    {
                        if (_buffer.Count > 0)
                        {
                            value = _buffer.Dequeue();
                        }
                        else
                        {
                            _ready.Reset();
                            continue;
                        }

                        if (((ConsoleForm)_output.Target).IsDisposed)
                            return;

                        try
                        {
                            base.Write(value);
                            _output(value);
                        }
                        catch (ObjectDisposedException e)
                        {
                            // Eat up the ObjectDisposedException.
                            string stackTrace = e.StackTrace;
                        }
                    }
                }
            }
            catch (ThreadInterruptedException)
            {
                _buffer.Clear();
                return;
            }
        }

        public override Encoding Encoding
        {
            get
            {
                lock (_sync)
                { return System.Text.Encoding.UTF8; }
            }
        }
    }