Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

On update the GUI from another thread in C# throws exception because the control on form running on main thread and programmer make changes to the control (e.g. TextBox) through another thread. The most common exception is System.InvalidOperationException occurred in System.Windows.Forms.dll


The easiest and the simplest way is to use anonymous method as following:


[code]

void OtherThreadMethod()

{

// running on the worker thread

string txt = updated text value;


// runs on UI (main) thread

this.Invoke((MethodInvoker)delegate { textBox1.Text = txt; });

}

[/code]


where:

textBox1 is the TextBox control on the form.

Posted Article in Programming
Login InOR Register