I have a C# multi-threaded app with a bunch of worker threads in different pools all calling this function to update a textbox in a WinForms app.
It has a very subtle bug (or maybe not if you know what you are doing) that results in an Out-Of-Memory exception over a long period of time (I think because the stack never gets to unroll, but I'm not sure).
What is the correct way to update a textbox from any thread in my app without encountering this issue? The root problem is Application.DoEvents, but I don't know how to force a GUI update without it (if I take it out, the GUI never updates).
Ideally the solution would be a function that I can call from any thread that just does the right thing.
private void WriteStatus(string s)
{
if (textBoxStatus.InvokeRequired)
{
textBoxStatus.Invoke(new Action<string>(WriteStatus), new object[] { s });
}
else
{
StringBuilder sb = new StringBuilder(s + Environment.NewLine);
sb.Append(textBoxStatus.Text.Substring(0, textBoxStatus.Text.Length > 40000 ? 40000 : textBoxStatus.Text.Length));
textBoxStatus.Text = sb.ToString();
// don't call DoEvents more than once a second - this prevents stack over flow from frequent updates
if (DateTime.Now - lastGUIUpdate > TimeSpan.FromSeconds(1))
{
Application.DoEvents();
lastGUIUpdate = DateTime.Now;
}
}
}
I've looked at other SO solutions for this problem, but they seem to ignore the Application.DoEvents step. How are they forcing their GUI to update in this circumstance? In my app commenting this line out fixes my memory problems, but my textbox never updates.