Posted by: Cirilo Meggiolaro | 10/30/2008

Tip of the day #16 – Executing delegates with ISynchronizeInvoke interface

Developers used to code multi thread applications know that UI controls cannot be accessed by a different thread other than the one that has created the controls.

To perform this task you will have to use the ISynchronizeInvoke interface under the System.ComponentModel namespace that allows your application to execute synchronously or asynchronously a delegate on the same thread that has created the controls.

Methods

1. BeginInvoke: Used to execute a delegate asynchronously;

2. Invoke: The Invoke method expects the same parameters than BeginInvoke but will be executed synchronously.

Properties

1. InvokeRequired: The boolean property checks if the current thread is different than the one that has created the control.

How to…

A quick example about how to use based on event and delegate.

public delegate void MyDelegate();
public event MyDelegate OnMyEvent;

/// Add the event handler on the form initialization
this.OnMyEvent += new MyDelegate(MyMethod);

void MyMethod()
{

ISynchronizeInvoke iSync = (ISynchronizeInvoke)this;

/// Check if the event was generated from another
/// thread and needs invoke instead

if (iSync.InvokeRequired)
{
MyDelegate myDelegate = new MyDelegate(OnMyEvent);

iSync.BeginInvoke(myDelegate, null);

return;
}

// If the request is not coming from a separate thread
// call the method that accesses the UI controls
MyMethodToUpdateControls();

}


Responses

  1. Very good tip. Thanks Cirilo!


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

Categories

%d bloggers like this: