Nathanael
Nathanael

Reputation: 141

How do I run function in vala asynchronously when a button is clicked

I am just starting out with Vala and have hit a hurdle

When I try and run a large function on a button press it locks the entire app up until it is finished

How would I put a something like the following into a thread or give it an asynchronous callback?

    var btn = new Gtk.Button();

    btn.label = "Run something massive!";

    btn.clicked.connect (() => {
        Process.spawn_command_line_sync("gksudo apt-get update",
                                        out ls_stdout,
                                        out ls_stderr,
                                        out ls_status);

        btn.set_sensitive (false);
    });

Upvotes: 2

Views: 339

Answers (1)

apmasell
apmasell

Reputation: 7153

In Gtk+, there is only one thread that processes GUI events. If you want to do a background process, you can either create a thread or split the task up and processes it in the main loop. I recommend the latter.

For launching a process, consider GLib.Process.spawn_async. To know when the process exits, you will have to install a handler using ChildWatch.

The example for ChildWatch is likely what you want.

Upvotes: 4

Related Questions