Wednesday, October 7, 2009

 

InvalidOperationException - "Cross-thread operation not valid..."

Most C# programmers have probably seen the infamous InvalidOperationException "Cross-thread operation not valid" exception at one time or another. When you see that, you instantly know that your code tried to access the property of a control from a thread other than the thread on which the control's window handle was created. If you recall a previous post of mine (or from MSDN), there are actually only a total of four methods and properties on a control that can be access from another thread:



Novice programmers may think these cross-thread exceptions are just nuisance messages that can be ignored because they do not happen in the final release build sent to the customer. That, however, couldn't be further from the truth. Rather, you should aggressively seek them out and fix them because they can lead to all kinds of unexplained lock-ups and crashes that are difficult to diagnose. But, in order to find them you have to know when you can see them!

I use to think that cross-thread exceptions are thrown in debug builds, but not thrown in release builds. That seems to be the way it works, at first, and makes sense to me as a programmer. After all, a simple #if (DEBUG) somewhere down in framework code could easily accomplish that. But, as I have found out the hard way, it is not that simple.

Rather, my experimentation has shown that cross-thread exceptions only occur if you actually started the application from within Visual Studio. If you run a debug build of the application from outside of Visual Studio, you do not get the cross-thread exceptions even if you "attached" Visual Studio to that application via the "Debug | Attach to Process..." menu.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]