redirect console.out to textbox

Joined
Jan 10, 2007
Messages
43,898
Location
In The Machine
hello all,
i'm working on a quiet old console application. It mainly calls various procedures, whose outputs are either on console or trace. Nothing graphical that is.
my first job was to make sure we got a permanent trace (as with the basic console.write() instructions, output is lost when application exits).
So i started by redirecting on file:

string fileName = ConfigurationManager.AppSettings["BatchOutput.LogFile"];
fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
sw = new StreamWriter(fs);
oldOut = Console.Out;
Console.WriteLine(DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " - " + string.Format("Redirecting output to {0}", fileName));
Console.SetOut(sw);
flusher = new System.Threading.Timer(new TimerCallback(delegate(object sender) { Console.Out.Flush(); }), new AutoResetEvent(true), 0, 1000);

Works fine. But now, i'm asked to develop a gui interface to replace the old console application, and have the output displayed in a textbox.
Quiet easy task: redirecting console.out to a texbox is no big deal, you (basically) just have to design some textwriter based class and override Write and Writeln methods:

*internal sealed class FeedbackWriter : TextWriter
*{
**(...)
**
**public override void Write(string value)
**{
***_textBox.AppendText(value);
**}
**
**public override void WriteLn(string value)
**{
***_textBox.AppendText(value + Environment.Newline);
**}

**(...)
*}

This would just have worked fine if i didn't forget one thing: the application starts various processes during run time. Those processes call Console.Write(). And as none of them created the TextBox, it ends with Cross Threading exceptions. So i googled the problem and end with a solution:


* delegate void addDelegate(string text);

* public override void Write(string value)
**{
***if (_textBox.InvokeRequired)
***{
****IAsyncResult res = _textBox.BeginInvoke(new addDelegate(_textBox.AppendText), value.Replace("\n", base.NewLine));
****_textBox.EndInvoke(res);
***}
***else
***{
****_textBox.AppendText(value);
***}
***Application.DoEvents();
**}

It should work, but for an unknown reason, calling _textBox.EndInvoke() will freeze the app. Same goes if i use _textBox.Invoke() instead of .StartInvoke(). And if i use .StartInvoke() without the subsequent .EndInvoke(), app will run normally, but the textbox will be "fed" when calling process ends (wich could take some minutes during wich we wouldn't see any output)
I tried with backgroundworkers and*got same results: either i get the output*when process exits, or the application freezes. Anyone got an idea why ?
Thanks
*


More...

View All Our Microsoft Related Feeds
 
Back
Top