Asynchronous WinForm UI

When you’re trying to create a WinForm Application that is working asynchronously, you’ll probably in a common failure:

System.InvalidOperationException occurred
Message="Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on."
Source="System.Windows.Forms"

You’ll get this failure, because it’s not allowed to update a UI control from another thread than the thread that has created the control.

A fluent way around this is to use the MethodInvoker class.
Let’s asume that you have a statement like the following one:

appForm.Text = appInfo;

Using the MethodInvoker class would look like:

appForm.Invoke(new MethodInvoker(() => { appForm.Text = appInfo; }));

That’s still a one-liner;-) And with that small hint, you’ll get around such annoying exceptions.
Hope you enoy it.

Cheers
– Gerhard

PS: Here’s also a great article about the MethodInvoker.

kick it on DotNetKicks.com

About these ads

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

Follow

Get every new post delivered to your Inbox.

Join 106 other followers

%d bloggers like this: