On GTK# and InvokeRequired


Most user interface code is not thread safe. If multiple threads change UI components, unexpected things may happen. .NET Windows Forms programmers are familiar with the InvokeRequired property present in all controls. It is common to find code of the following kind in callback methods:

private void MyCallback()
{
  if (!InvokeRequired)
  {
     // do something useful
  }
  else
  {
    Invoke(new MethodInvoker(delegate
    {
      // Anonymous delegate
      // Things to do in the UI thread
    }));
  }
}

In GTK# this works slightly differently. To queue work to the UI thread use the static method Add from the Idle class in the GLib namespace. Here’s some example code.

private void MyCallback()
{
  GLib.Idle.Add(new IdleHandler(MyHandler));
}
private bool MyHandler()
{
  // do something useful
  return false; // return true if the idle handler must be called again
}

GTK# 2 has another method that can be used with anonymous delegates, Gtk.Application.Invoke. Its usage is described in the article Responsive Applications.

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