OpenNETCF Extensions: Eliminating Control.Invoke

Marshaling UI access to the proper thread is a very common task in app development, yet it still tends to be a pain in the ass.  You have to check if InvokeRequired is true (well you probably don’t *have* to, but not doing it feels dirty to me) and even using an anonymous delegate tends to be verbose.  And then there are also the simple bugs that are not always easy to spot.

So, like any good developer, I stole someone else’s idea and put it into the OpenNETCF Extensions.  Now, instead of doing this:

void MyMethod()
{
    if (this.InvokeRequired)
    {
        this.Invoke(new EventHandler(delegate
            {
                MyMethod();
            }));
        return;
    }

    // do stuff with the UI
}

You do this:

void MyMethod()
{
    Invoker.InvokeIfRequired(i =>
    {
        // do stuff with the UI
    });
}

Less code.  Less potential for error.  More readable.  What’s not to like?


The OpenNETCF Extensions library is a collection of extension methods and helper classes that I find useful in a lot of different projects. It’s compatible with the Compact Framework, Tirethe full framework and Windows Phone.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s