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)

{

this.CreateHandle();

}

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…

14 comments:

Anonymous said...

thanks man

Eralp,from Turkey

www.eralperat.com

ecommercewebmaster12 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 http://www.infyecommercesolution.com immediately and facilitate your online business.

dghnfgj said...

In English class, one girl Cheap WoW Gold said never give up when discussing. It just reminded me wow goldsomething about myself.WoW Gold Maybe it is wow power leveling something about love.WoW Gold My love, which began on July 3rd of WoW Gold 2005 and finished on August wow leveling 23rd of 2008, taught me many things. wow leveling It is not a pleasant world of warcraft power leveling thing to look back on world of warcraft power leveling that. But I know I world of warcraft power leveling must learn something from it,world of warcraft leveling no matter what it is, world of warcraft leveling happiness or sorrow.Our wow gold love did not go on so smoothly and we went through many things.

lee 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.

Game player said...

I can get twelve sky Gold cheaply,
Yesterday i want to buy 12sky goldfor my brother.
i hope him like it. i will buy twelvesky Gold for him
as birthday present. i like the 12Sky Silver Coins very much.
I usually buy 12 sky gold and keep it in my store.
I can get FFXI Gil cheaply.
Yesterday i bought FFXI goldfor my brother.
i hope him like it. i will give Final Fantasy XI gold to him
as birthday present. i like the cheap Final Fantasy XI Gold very much.
I usually buy FFXI Gil and keep it in my store.

said...

You know ,I have some maple mesos,and my friend also has some
mesos,do you kouw they have the same meaning,Both of them can be called
maplestory mesos,I just want to
buy flyff penya ,because there are many
cheap mesos


You know ,I have some requiem gold,and my friend also has some
requiem lant,do you kouw they have the same meaning,Both of them can be called requiem money,I just want to
requiem online gold,because there are many
cheap requiem lant

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.

lanzi said...

I can get Solstice Kron cheaply.
Yesterday i bought Solstice Online Kronfor my brother.
i hope him like it. i will give Solstice Gold to him
as birthday present. i like the Solstice Online money very much.
I usually buy cheap Solstice Kron and keep it in my store.


I can get Solstice Kron cheaply.
Yesterday i bought Solstice Online Kronfor my brother.
i hope him like it. i will give Solstice Gold to him
as birthday present. i like the Solstice Online money very much.
I usually buy cheap Solstice Kron and keep it in my store.

yinghong 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 Gameim.com 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...

latale online gold in the game. We know, the latale gold can exchange the real money of the reality. The world you are enjoying in latale money can entertainment. This economic structure lead buy latale online gold has one kinds of real value. You can use cheap latale gold to purchase various items of course.
The 12sky2 Gold should be a timely evolution of the world. Please step up efforts to investigate all types of twelve sky2 Gold can be set up in the game. twelvesky2 Gold to add more rudimentary fashion. The buy 12sky2 Gold can help you combat equipment of the production. Use the cheap twelve sky2 Gold may change the door to door battle.

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...