This example shows how to make a multi-threaded handler for the built in Console commands.
You can set Console.Out to any TextWriter. So you simply have to create your own TextWriter to handle cross-threaded handling of messages to your user interface.
Below is an example of a writing Console messages to a TextBox from two different threads.
TextBoxOutputter.cs
using
System;
using
System.IO;
using
System.Text;
using
System.Windows.Controls;
namespace
WpfApplication68
{
public
class
TextBoxOutputter : TextWriter
{
TextBox textBox =
null
;
public
TextBoxOutputter(TextBox output)
{
textBox = output;
}
public
override
void
Write(
char
value)
{
base
.Write(value);
textBox.Dispatcher.BeginInvoke(
new
Action(() =>
{
textBox.AppendText(value.ToString());
}));
}
public
override
Encoding Encoding
{
get
{
return
System.Text.Encoding.UTF8; }
}
}
}
Note: It's using the TextBox's Dispatcher to append the text. This prevents threading problems.
MainWindow.xaml
<
Window
x:Class
=
"WpfApplication68.MainWindow"
Title
=
"MainWindow"
Height
=
"350"
Width
=
"525"
xmlns:local
=
"clr-namespace:WpfApplication68"
>
<
Grid
>
<
TextBox
Height
=
"200"
Width
=
"400"
x:Name
=
"TestBox"
/>
</
Grid
>
</
Window
>
MainWindow.xaml.cs
using
System;
using
System.Windows;
using
System.Threading;
namespace
WpfApplication68
{
public
partial
class
MainWindow : Window
{
TextBoxOutputter outputter;
public
MainWindow()
{
InitializeComponent();
outputter =
new
TextBoxOutputter(TestBox);
Console.SetOut(outputter);
Console.WriteLine(
"Started"
);
var timer1 =
new
Timer(TimerTick,
"Timer1"
, 0, 1000);
var timer2 =
new
Timer(TimerTick,
"Timer2"
, 0, 500);
}
void
TimerTick(
object
state)
{
var who = state
as
string
;
Console.WriteLine(who);
}
}
}
This small article is part of a series of WPF "How To" articles, in response to real user questions on the MSDN WPF Forum.