Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access GUI (GTK) from multi threads?

Tags:

c#

mono

gtk

gtk#

I have a worker thread spawned from a GUI (for GUI performance), how do I access GUI, such as spawning new windows/widgets from the thread itself?

I tried using delegates but it doesn't seem to be working. Any ideas? Possibly examples? Thank you.

like image 714
nubela Avatar asked Mar 30 '10 19:03

nubela


People also ask

Is GTK multithreaded?

GTK+ is "thread aware" but not thread safe — it provides a global lock controlled by gdk_threads_enter() / gdk_threads_leave() which protects all use of GTK+. That is, only one thread can use GTK+ at any given time.

Is GTK single threaded?

GTK is also single threaded and not MT-safe. This means, that you must not call any GTK functions from other threads, as it will lead to undefined behaviour.


1 Answers

According to their Best Practices:

Gtk# is not a thread-safe toolkit, which means that only one thread at a time can safely invoke methods on Gtk#. This thread is typically the thread executing the main loop (which is when control has been explicitly transfered to Gtk).

When application developers need to have threads update some element of the graphical user interface they have to either acquire a lock that allows them to issue Gtk# toolkit invocations or they can make their code execute on the same thread as the one thread that executes the main loop.

To invoke a method on the GTK+ main loop thread and avoid any threading problems with GTK, you can use the Gtk.Application.Invoke() method (if you are targetting Gtk# 1.0 you can use Gtk.ThreadNotify).

The following example is provided; you should use Invoke to execute any Gtk code from within the main loop:

public void ThreadedMethod()
{
    Gtk.Application.Invoke(delegate {
        do_stuff_in_main_thread();
    });
}
like image 86
Justin Ethier Avatar answered Oct 03 '22 22:10

Justin Ethier