Andy's observations as he continues to attempt to know all that is .NET...

Thursday, July 06, 2006

Custom Controls and Cross Threading

In .NET 2.0 a feature was introduced so as to raise an exception if an application attempted to access a Windows Control on a thread other than the thread in which the control was initially rendered. This is because Windows Controls are deemed not thread safe, and only expect to interact with a single thread, and thus have no state lock protection. In 1.1 you could blissfully ignore this and most of the time your code would work..

The feature in 2.0 is disabled by default, but when you run under the debugger it is enabled. The debugging environment sets the static member on the Control class CheckForIllegalCrossThreadCalls to true.

Whenever you attempt to get hold of the underlying Windows handle for the control this static member is first inspected and if it evaluates to true the InvokeRequired method is invoked to see if you are indeed on the correct thread. If you are not on the correct thread the exception is thrown

The code below was generated by Reflector, taken from the base Control class

public IntPtr get_Handle()


if ((Control.checkForIllegalCrossThreadCalls && !Control.inCrossThreadSafeCall) && this.InvokeRequired)


throw new InvalidOperationException(SR.GetString("IllegalCrossThreadCall",

new object[] { this.Name }));


if (!this.IsHandleCreated)




return this.HandleInternal;


There is a slight extra piece of complication in that it is possible to have some control operations that are thread safe, these calls use a class called Control.MultithreadSafeCalllScope which implements IDisposable as a way to wrapup blocks of code that are in fact thread safe and still need to have access to the underlying windows handle.

So using Reflectors Analyze feature I decided to see where this class was used in the framework so that you can see what Windows control methods are Thread safe…

The results were as follows

System.Windows.Forms.Control.BeginInvoke(Delegate, Object[]) : IAsyncResult

System.Windows.Forms.Control.CreateGraphics() : Graphics

System.Windows.Forms.Control.EndInvoke(IAsyncResult) : Object

System.Windows.Forms.Control.get_InvokeRequired() : Boolean

System.Windows.Forms.Control.get_WindowText() : String

System.Windows.Forms.Control.Invalidate(Boolean) : Void

System.Windows.Forms.Control.Invalidate(Rectangle, Boolean) : Void

System.Windows.Forms.Control.Invalidate(Region, Boolean) : Void

System.Windows.Forms.Control.Invoke(Delegate, Object[]) : Object

A few posts back I saw that Invalidate was possible, but now I can see that I can also get the text associated with a windows control.

Anyway back to the plot….the reason for all this was to make my own custom controls behave the same as the underlying windows controls. I basically wanted to ensure that my control was only ever interacted with on a single thread. Since with UI apps you generally expect everything to happen on the main UI thread you don’t want to put the overhead of locking etc in as the majority of cases everything is happening on the UI thread.

So I’ve added a new method to my control called CheckForIllegalCrossCall I make a call to this method inside each of my properties..

private void CheckForIllegalCrossCall()


if ((Control.CheckForIllegalCrossThreadCalls) && (InvokeRequired))


throw new InvalidOperationException("Illegal cross Thread operation");



Now I don’t need to worry about state corruption as state can now only be manipulated on a single thread. When debugging we will make the call to InvokeRequired and when not we will simply assume that the programmer knows what he’s doing…


Anonymous said...

thanks man

Eralp,from Turkey

Anonymous said...

In order to make money online in the best possible way, you need to figure out effective business strategies and we can help you with that. We, at Infinity Informations, are well known all over for providing efficient business solutions to our clients all over the world and as soon as you utilize our ecommerce solutions for the purpose of facilitating your online business, you would notice sudden and tremendous growth in your ecommerce venture. So, contact immediately and facilitate your online business.

Anonymous said...

China Highlights
China Highlights
China Tours
China Hotels
China Attractions
Beijing China Travel
Shanghai China Travel
Xi'an China Travel
Guilin China Travel
Yangshuo China Travel

Anonymous said...

Do you know the warhammer gold, In here you can buy the warhammer Online gold, Do you know that the warhammer money in the game is very important, If you had more cheap warhammer Online gold . I think you can get the tall level, quickly come here to buy warhammer gold.

world of warcraft gold said...

Weaknesses of World Of Warcraft Gold the client-server model used by World of Warcraft have been wow power levelingexploited in order to crash the cluster of servers that aoc goldmake up a realm. Exploits also include characters being able to instantly Cheapest Wow Goldchange location or teleport. The situationbecame worse cheap wow goldwhen trying to coordinate activities across a number of playersor guilds on the same realm.World of Warcraft Lead Producer, stated that new realms would be introduced to warhammer goldrelieve the burden on existing ones. Existing realms would be upgraded.

Although the game wow gold follows a similar model to others in the genreand was noted for having wow gold cheapmany familiar concepts from roleplaying games, the new approaches gold4powerto reduce pauses between game encounters was well liked. At various times, World of Warcraft players have experienced problems with connecting to and logging in to wow gold for sale the game. Sudden server crashes that would force realms offline also occurred.

Anonymous said...

runescape gold of RS Online Game, we have made several changes to Fun Orb. If you wish to buy runescape to explore other spell books, you should subscribe as a Fun Orb member. Shattered Plans - a galaxy-spanning strategy epic that use rs gold to allow up to six players to battle for supremacy. We only plan to pay cheap rs gold when we feel you will appreciate the updates. And we certainly feel that these changes and some runescape money are worth telling you about.
Scions Of Fate gold is sometimes need to pay for in this Scions of Fate game. For example in this game, we have to buy sof gold to exchange premium in order to protect our character. The only part of this game will require you to pay SOF gold but they are optional for you to choose in the premium store. One very common item bought with cheap SOF gold at the store would be a pet. The is offering you with Scions Of Fate money and all kinds of cheap game gold.

Anonymous said...

You know ,I have some priston tale Gold, and my friend also has some
priston tale Money, do you kouw they have the same meaning,I just want to
buy priston tale Gold, because there are many
cheap priston tale Gold.
You know ,I have some shadow of legend Gold, and my friend also has some
sol gold, do you kouw they have the same meaning,Both of them can be called
shadow of legend money,I just want to
buy shadow of legend Gold, because there are many
cheap shadow of legend Gold.

Anonymous said...

We have holic gold. He gave me some holic money, he said that I could buy holic online gold, but I did not have money, then I played it all my spare time. From then on, I got some cheap holic gold. We also sell holic online moneyI did not know how to get strong, someone told me that you must have last chaos gold. He gave me some lastchaos gold, he said that I could buy last chaos gold, but I did not have money, then I played it all my spare time. From then on, I got some lastchaos money, if I did not continue to play it, I can sell cheap lastchaos gold to anyone who want.

Anonymous said...

Making World of Kung fu Gold is the old question : Honestly there is no fast way to make lots of WoKf gold . Sadly enough a lot of the people that all of a sudden come to with millions of buy World of Kung fu Gold almost overnight probably duped . Although there are a lot of ways to make lots of cheap World of Kung fu Gold here I will tell you all of the ways that I know and what I do to buy World of Kung fu money.

As a new player , you may need some game guides or information to enhance yourself.
wow gold is one of the hardest theme for every class at the beginning . You must have a good way to manage your World of Warcraft Gold.If yor are a lucky guy ,you can earn so many warcraft gold by yourself . But if you are a not , I just find a nice way to buy wow gold. If you need , you can buy cheap wow gold at our website . Go to the related page and check the detailed information .

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...