Gdk.Threads Class

See Also: Threads Members


public class Threads


Functions for using GDK in multi-threaded programs

For thread safety, Gdk relies on the thread primitives in GLib, and on the thread-safe GLib main loop.

GLib is completely thread safe (all global data is automatically locked), but individual data structure instances are not automatically locked for performance reasons. So e.g. you must coordinate accesses to the same GHashTable from multiple threads.

Gtk# is "thread aware" but not thread safe ? it provides a global lock controlled by Threads.Enter()/Threads.Leave() which protects all use of Gtk. That is, only one thread can use Gtk at any given time.

You must call Threads.Init() before executing any other Gtk or Gdk functions in a threaded Gtk# program.

Idles, timeouts, and input functions are executed outside of the main Gtk lock. So, if you need to call Gtk inside of such a callback, you must surround the callback with a Threads.Enter()/Threads.Leave() pair. (However, signals are still executed within the main Gtk lock.)

In particular, this means, if you are writing widgets that might be used in threaded programs, you must surround timeouts and idle functions in this matter.

As always, you must also surround any calls to Gtk not made within a signal handler with a Threads.Enter()/Threads.Leave() pair. Before calling Threads.Leave() from a thread other than your main thread, you probably want to call gdk_flush() to send all pending commands to the windowing system. (The reason you do not need to do this from the main thread is that GDK always automatically flushes pending commands when it runs out of incoming events to process and has to sleep while waiting for more events.)

A minimal main program for a threaded GTK+ application looks like:

C# Example

static void Main (string[] args)
  Window window;

  Gdk.Threads.Init ();
  Gtk.Application.Init ();

  window = new Window ("Sample");
  window.Show ();

  Gdk.Threads.Enter ();
  Gtk.Application.Run ();
  Gdk.Threads.Leave ();

  return 0;


Namespace: Gdk
Assembly: gdk-sharp (in gdk-sharp.dll)
Assembly Versions: