Bouncing Ma'ss

Techinical bits from a Bouncing Fish.

Tuesday, February 28, 2006

Updating a form / control from another thread

A common problem this must, as VS2005 Exception dialog walked me through the fix nicely.
So I get you can update a control from different threads, but I didn't think a timer callback counted as a separate thread. Duh!

Well it does and VS will throw an exception when you try and access a control from a separate thread, always in debug mode and sometimes in release mode.

In debug the exception box will lead you to this article directly.

Which simply tells you to do some stuff with a controls Invoke method and InvokeRequired property.

Before the offending code add this check:

if (this.InvokeRequired)
{
//Make a delegate version of this function and call:
this.Invoke (delegateObject, [parameters]);
}
else
{
//As normal
}


Pretty easy, best to do it at the event handler that the timer calls or fires.

1 Comments:

At 9:07 am, Blogger Shak said...

Alternatively you can just send a windows message to (or fire an event of) your target thread. I like this way better though.

 

Post a Comment

<< Home