Thread-safe form method

If you use threads in a winforms application, you probably have already encountered the classic InvalidOperationException saying that you are trying to make an illegal cross-thread operation. This is because you cannot modify a control from a thread other than the one that created it.
Here is a simple way to write your methods in the form to avoid that exception :
void SomeMethod(SomeType parameter)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(delegate()
{ this.SomeMethod(parameter); }));
}
else
{
// Do what SomeMethod is supposed to do.
}
}

You can use Invoke instead of BeginInvoke if you want to make an asynchronous call to the delegate.
Notice the anonymous method (delegate() {...}) used to invoke the same instruction in the correct thread.

Comments

Popular posts from this blog

Create a draft release and start it using the TFS REST API

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application