Archive

Posts Tagged ‘invoke’

A little more of the Invoke magic

February 22nd, 2008 Bobby Alexander No comments

A query by one of my colleagues prompted me to add this addendum to my Invoke article. He wanted to know whether you would ever need to invoke an event and if so, why.

The answer is yes and the reason is pretty simple actually. Remember what I said about invoke in the previous article? If you wanted to modify a control’s properties from any thread other than the one it was created on, you will have to use invoke to call a delegate which would in turn call a method which would be executed on the thread on which the control was created on. The method, of course would contain the code to modify the control.

Now if you were to fire an event, and the handler for that event were to modify a control that was created on the main thread, it would throw an exception. This is because, since the event was fired on the non-UI thread, the handler for that event will end up being executed in the same thread and as we know by now, this is illegal.

The solution is, of course, to use invoke. So the event to modify a progress bar would look like this:

this.Invoke(updateProgressEvent,new object[]{updateValue});

Without using invoke this event would have been fired like this:

updateProgressEvent(updateValue);

Its pretty simple when you understand why :)

P.S: Guess what? I actually managed to keep this short.

Code Safely
Alex

Categories: Uncategorized Tags: , ,