Saturday 21 November 2009

InvalidOperationException: Cross-thread Operation Not Valid

DO NOT mess with Windows Forms Controls (even just READING a text field is BAD NEWS) from a a thread other than the GUI thread (unless a) you use Invoke, b) don't know anything about Windows programming. The following "wisdom-sommaire" from MSDN summarises aforesaid most appositely:

"If you use multithreading to improve the performance of your Windows Forms applications, you must make sure that you make calls to your controls in a thread-safe way. Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible, such as race conditions and deadlocks. It is important to make sure that access to your controls is performed in a thread-safe way. It is unsafe to call a control from a thread other than the one that created the control without using the Invoke method."

As aforesaid, even reading a text box is bad news, amigos. I can't say this enough times:

Access to Windows Forms controls is not inherently thread safe.
Access to Windows Forms controls is not inherently thread safe.
Access to Windows Forms controls is not inherently thread safe.

Failure to comply WILL result in IOE. But what about WPF?

No comments: