Cross threading problem with updating UI in WinForms

While trying to make a Windows application more responsive, i ended up cross threading, that is, i had one thread starting my application and another thread performing the work but trying to update the UI (a textbox) after the processing was done.

The solution is to call the Invoke method on the UI control as follows:

public delegate void UpdateTextboxHandler(string message);

private void UpdateTextbox(string message)
{
textBox1.Text += message;
}

private void Process_OnFinishProcessing(string message)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new UpdateTextboxHandler(UpdateTextbox), message);
}
else
{
textBox1.Text += message;
}
}

More information can be found on Multithreading with Windows Forms

comments powered by Disqus