I have a BackgroundWorker
thread that is posting messages, using BeginInvoke
on a textbox in the GUI. The method, write_debug_text
, that displays text in the textbox uses AppendText
and also writes the text to the Console
.
The appearance is that the BackgroundWorker
is writing too fast for the write_debug_text
to keep up. I set a breakpoint at write_debug_text
and have to wait a long time before it is hit. Many calls to 'BeginInvoke` occur before the breakpoint is hit.
I'm looking for a real-time display of messages on the UI, much like the System.Console
in the VS C# Express IDE.
From searching on SO, I understand that AppendText
is the faster method to use and that strings may have to be reallocated.
Some replies suggest using StringBuilder
then periodically writing that text to the textbox. But this requires adding more events and timers; which I would rather not do (my simple application keeps getting more and more complex).
How can I either write real-time to the Textbox (and have it display)?
My current idea is to create a widget inheriting from Textbox that uses a text queue and timer.
Here is a fragment of my code:
private m_textbox;
//...
m_textbox.BeginInvoke(new write_debug_text_callback(this.write_debug_text),
new object[] { debug_text });
return;
private void write_debug_text(string text)
{
string time_stamp_text = "";
time_stamp_text = DateTime.Now.ToString() + " ";
time_stamp_text += text;
m_textbox.AppendText(time_stamp_text);
m_textbox.Update();
System.Console.Write(time_stamp_text);
return;
}
I have tried changing BeginInvoke
to Invoke
and my application is hung. When I pause / break using the debugger, the execution pointer is on the call to Invoke
.
BTW, I've got many years experience with Java, C++, and C. I am on my 5th month with C#.
I used @Jeffre L. Whitledge's advice and reduce the number of string allocations. Since this is a closed application with a fixed number of strings, I cached the strings. This produced a side-effect of my program executing significantly faster.
One of my issues is still the slowness in Windows responding to messages. This can be seen when the progress bar is updated. There is a definite delay from when a message is sent (such as append text), and when it is performed.