Invoke with Whidbey

Fri, October 1, 2004, 05:30 AM under Whidbey | VisualStudio
Last time we looked at Control.Invoke on both CF and full framework. Assuming you have read it, let’s look at VS2005.

On the desktop, if you forget to use Control.Invoke, you now get an InvalidOperationException with the Message: "Illegal cross-thread operation: Control 'SomeControlName' accessed from a thread other than the thread it was created on." That is cool, and the stack trace will of course point you to the culprit. Note this only works when debugging in the IDE, and is not available to CF projects. Instead, with Smart Device projects, you get the (catchable) System.NotSupportedException (with the Beta 1 bits).

CF 2.0 brings parity with the desktop; all 3 limitations are removed, so you don't need the ThreadPool or the Queue or the need to cast:

// ...or any other type/params you want
delegate void SomeCustomDelegate(object o);

// This method runs on a non-GUI thread e.g. Threading.Timer
internal void OnNonGuiThread(Object o){
// if you have more than one argument just add it to the array
object[] arr = {o};

// assuming all this code is in a form
this.BeginInvoke(new SomeCustomDelegate(UpdateBox), arr);

// This method runs on GUI thread
private void UpdateBox(Object o
/*other arguments as defined by SomeCustomDelegate*/){

// TODO use o and other arguments
this.Text = o.ToString();