About all my projects
Gnome::Gio::Task

Gnome::Gio::Task

Description

A Gnome::Gio::Task represents and manages a cancellable ‘task’.

Asynchronous operations

The most common usage of Gnome::Gio::Task is as a Gnome::Gio::Task, to manage data during an asynchronous operation. You call .newtask() in the ‘start’ method, followed by .set-task-data() and the like if you need to keep some additional data associated with the task, and then pass the task object around through your asynchronous operation. Eventually, you will call a method such as .return-pointer() or .return-error(), which will save the value you give it and then invoke the task’s callback function in the thread-default main context (see .push-thread-default() in class Gnome::Gio::Task) where it was created (waiting until the next iteration of the main loop first, if necessary). The caller will pass the Gnome::Gio::Task back to the operation’s finish function (as a Gnome::Gio::Task), and you can use .propagate-pointer() or the like to extract the return value.

Using Gnome::Gio::Task requires the thread-default MainContext from when the Gnome::Gio::Task was constructed to be running at least until the task has completed and its data has been freed.

If a Gnome::Gio::Task has been constructed and its callback set, it is an error to not call g_task_return_*()` on it. GLib will warn at runtime if this happens (since 2.76).

Here is an example for using Gnome::Gio::Task as a Gnome::Gio::Task:

Chained asynchronous operations

Gnome::Gio::Task also tries to simplify asynchronous operations that internally chain together several smaller asynchronous operations. .get-cancellable(), .get-context(), and .get-priority() allow you to get back the task’s Gnome::Gio::Task, MainContext , and [I/O priority](iface.AsyncResult.html#io-priority) when starting a new subtask, so you don’t have to keep track of them yourself. .attach-source() simplifies the case of waiting for a source to fire (automatically using the correct MainContext and priority).

Here is an example for chained asynchronous operations:

Asynchronous operations from synchronous ones

You can use .run-in-thread() to turn a synchronous operation into an asynchronous one, by running it in a thread. When it completes, the result will be dispatched to the thread-default main context (see .push-thread-default() in class Gnome::Gio::Task) where the Gnome::Gio::Task was created.

Running a task in a thread:

Adding cancellability to uncancellable tasks

Finally, .run-in-thread() and .run-in-thread-sync() can be used to turn an uncancellable operation into a cancellable one. If you call .set-return-on-cancel(), passing True, then if the task’s Gnome::Gio::Task is cancelled, it will return control back to the caller immediately, while allowing the task thread to continue running in the background (and simply discarding its result when it finally does finish). Provided that the task thread is careful about how it uses locks and other externally-visible resources, this allows you to make ‘GLib-friendly’ asynchronous and cancellable synchronous variants of blocking APIs.

Cancelling a task:

Porting from Gnome::Gio::Task

Gnome::Gio::Task’s API attempts to be simpler than Gnome::Gio::Task’s in several ways:

  • You can save task-specific data with .set-task-data(), and retrieve it later with .get-task-data(). This replaces the abuse of .set-op-res-gpointer() in class Gnome::Gio::SimpleAsyncResult for the same purpose with Gnome::Gio::Task.

  • In addition to the task data, Gnome::Gio::Task also keeps track of the [priority](iface.AsyncResult.html#io-priority), Gnome::Gio::Task, and MainContext associated with the task, so tasks that consist of a chain of simpler asynchronous operations will have easy access to those values when starting each sub-task.

  • .return-error-if-cancelled() provides simplified handling for cancellation. In addition, cancellation overrides any other Gnome::Gio::Task return value by default, like Gnome::Gio::Task does when .set-check-cancellable() in class Gnome::Gio::SimpleAsyncResult is called. (You can use .set-check-cancellable() to turn off that behavior.) On the other hand, .run-in-thread() guarantees that it will always run your task_func, even if the task’s Gnome::Gio::Task is already cancelled before the task gets a chance to run; you can start your task_func with a .return-error-if-cancelled() check if you need the old behavior.

  • The ‘return’ methods (eg, .return-pointer()) automatically cause the task to be ‘completed’ as well, and there is no need to worry about the ‘complete’ vs ‘complete in idle’ distinction. (Gnome::Gio::Task automatically figures out whether the task’s callback can be invoked directly, or if it needs to be sent to another MainContext , or delayed until the next iteration of the current MainContext .)

  • The ‘finish’ functions for Gnome::Gio::Task based operations are generally much simpler than Gnome::Gio::Task ones, normally consisting of only a single call to .propagate-pointer() or the like. Since .propagate-pointer() ‘steals’ the return value from the Gnome::Gio::Task, it is not necessary to juggle pointers around to prevent it from being freed twice.

  • With Gnome::Gio::Task, it was common to call .propagate-error() in class Gnome::Gio::SimpleAsyncResult from the _finish()` wrapper function, and have virtual method implementations only deal with successful returns. This behavior is deprecated, because it makes it difficult for a subclass to chain to a parent class’s async methods. Instead, the wrapper function should just be a simple wrapper, and the virtual method should call an appropriate g_task_propagate_ function. Note that wrapper methods can now use .legacy-propagate-error() in class Gnome::Gio::R-AsyncResult to do old-style Gnome::Gio::Task error-returning behavior, and .is-tagged() in class Gnome::Gio::R-AsyncResult to check if a result is tagged as having come from the _async()` wrapper function (for ‘short-circuit’ results, such as when passing 0 to .read-async() in class Gnome::Gio::InputStream).

Thread-safety considerations

Due to some infelicities in the API design, there is a thread-safety concern that users of Gnome::Gio::Task have to be aware of:

If the Gnome::Glib::T-lib thread drops its last reference to the source object or the task data before the task is finalized, then the finalizers of these objects may be called on the worker thread.

This is a problem if the finalizers use non-threadsafe API, and can lead to hard-to-debug crashes. Possible workarounds include:

  • Clear task data in a signal handler for notify::completed`

  • Keep iterating a main context in the main thread and defer dropping the reference to the source object to that main context when the task is finalized

Uml Diagram

No caption

Class initialization

new

:native-object

Create an object using a native object from an object of the same type found elsewhere. See also Gnome::N::TopLevelSupportClass.

multi method new ( N-Object() :$native-object! )

new-task

Creates a Gnome::Gio::Task acting on $source-object, which will eventually be used to invoke $callback in the current thread-default main context.

Call this in the "start" method of your asynchronous method, and pass the Gnome::Gio::Task around throughout the asynchronous operation. You can use .set-task-data() to attach task-specific data to the object, which you can retrieve later via .get-task-data().

By default, if $cancellable is cancelled, then the return value of the task will always be G_IO_ERROR_CANCELLED, even if the task had already completed before the cancellation. This allows for simplified handling in cases where cancellation may imply that other objects that the task depends on have been destroyed. If you do not want this behavior, you can use .set-check-cancellable() to change it.

method new-task ( gpointer $source-object, N-Object() $cancellable, GAsyncReadyCallback &callback, gpointer $callback-data --> Gnome::Gio::Task \)
  • $source-object; the Gnome::GObject::Object that owns this task, or undefined..

  • $cancellable; optional Gnome::Gio::Cancellable object, undefined to ignore..

  • GAsyncReadyCallback &callback; a Gnome::Gio::T-iotypes.. The function must be specified with the following signature; :( N-Object $source-object, N-Object $res, gpointer $data ).

  • $callback-data; user data passed to $callback..

Methods

attach-source

A utility function for dealing with async operations where you need to wait for a Gnome::Glib::N-Source to trigger. Attaches $source to $task's Gnome::Glib::N-MainContext with $task's [priority](iface.AsyncResult.html#io-priority), and sets $source's callback to $callback, with $task as the callback's user_data.

It will set the $source’s name to the task’s name (as set with .set-name()), if one has been set on the task and the source doesn’t yet have a name.

This takes a reference on $task until $source is destroyed.

method attach-source ( N-Object $source, GSourceFunc &callback )
  • $source; the source to attach

  • GSourceFunc &callback; the callback to invoke when $source triggers. The function must be specified with the following signature; :( gpointer $user-data ).

get-cancellable

Gets $task's Gnome::Gio::Cancellable

method get-cancellable (--> N-Object )

Return value; $task's Gnome::Gio::Cancellable.

get-check-cancellable

Gets $task's check-cancellable flag. See .set-check-cancellable() for more details.

method get-check-cancellable (--> Bool )

Return value; No documentation about its value and use.

get-completed

Gets the value of Gnome::Gio::Task:completed. This changes from False to True after the task’s callback is invoked, and will return False if called from inside the callback.

method get-completed (--> Bool )

Return value; True if the task has completed, False otherwise..

get-context

Gets the Gnome::Glib::N-MainContext that $task will return its result in (that is, the context that was the thread-default main context at the point when $task was created).

This will always return a non-undefined value, even if the task's context is the default Gnome::Glib::N-MainContext.

method get-context (--> N-Object )

Return value; $task's Gnome::Glib::N-MainContext.

get-name

Gets $task’s name. See .set-name().

method get-name (--> Str )

Return value; $task’s name, or undefined.

get-priority

Gets $task's priority

method get-priority (--> Int )

Return value; $task's priority.

get-return-on-cancel

Gets $task's return-on-cancel flag. See .set-return-on-cancel() for more details.

method get-return-on-cancel (--> Bool )

Return value; No documentation about its value and use.

get-source-object

Gets the source object from $task. Like g_async_result_get_source_object(), but does not ref the object.

method get-source-object (--> gpointer )

Return value; $task's source object, or undefined.

get-source-tag

Gets $task's source tag. See .set-source-tag().

method get-source-tag (--> gpointer )

Return value; $task's source tag.

get-task-data

Gets $task's task_data.

method get-task-data (--> gpointer )

Return value; $task's task_data..

had-error

Tests if $task resulted in an error.

method had-error (--> Bool )

Return value; True if the task resulted in an error, False otherwise..

propagate-boolean

Gets the result of $task as a #gboolean.

If the task resulted in an error, or was cancelled, then this will instead return False and set $error.

Since this method transfers ownership of the return value (or error) to the caller, you may only call it once.

method propagate-boolean ( CArray[N-Error] $err --> Bool )
  • $err; Error object. When defined, an error can be returned when there is one. Use Pointer when you want to ignore the error. .

Return value; the task result, or False on error.

propagate-int

Gets the result of $task as an integer (#gssize).

If the task resulted in an error, or was cancelled, then this will instead return -1 and set $error.

Since this method transfers ownership of the return value (or error) to the caller, you may only call it once.

method propagate-int ( CArray[N-Error] $err --> Int )
  • $err; Error object. When defined, an error can be returned when there is one. Use Pointer when you want to ignore the error. .

Return value; the task result, or -1 on error.

propagate-pointer

Gets the result of $task as a pointer, and transfers ownership of that value to the caller.

If the task resulted in an error, or was cancelled, then this will instead return undefined and set $error.

Since this method transfers ownership of the return value (or error) to the caller, you may only call it once.

method propagate-pointer ( CArray[N-Error] $err --> gpointer )
  • $err; Error object. When defined, an error can be returned when there is one. Use Pointer when you want to ignore the error. .

Return value; the task result, or undefined on error.

propagate-value

Gets the result of $task as a Gnome::GObject::N-Value, and transfers ownership of that value to the caller. As with .return-value(), this is a generic low-level method; .propagate-pointer() and the like will usually be more useful for C code.

If the task resulted in an error, or was cancelled, then this will instead set $error and return False.

Since this method transfers ownership of the return value (or error) to the caller, you may only call it once.

method propagate-value ( N-Object $value, CArray[N-Error] $err --> Bool )
  • $value; return location for the Gnome::GObject::N-Value

  • $err; Error object. When defined, an error can be returned when there is one. Use Pointer when you want to ignore the error. .

Return value; True if $task succeeded, False on error..

return-boolean

Sets $task's result to $result and completes the task (see .return-pointer() for more discussion of exactly what this means).

method return-boolean ( Bool() $result )
  • $result; the #gboolean result of a task function..

return-error

Sets $task's result to $error (which $task assumes ownership of) and completes the task (see .return-pointer() for more discussion of exactly what this means).

Note that since the task takes ownership of $error, and since the task may be completed before returning from .return-error(), you cannot assume that $error is still valid after calling this. Call g_error_copy() on the error if you need to keep a local copy as well.

See also .return-new-error(), .return-new-error-literal().

method return-error ( N-Object $error )
  • $error; (transfer ownership: full) the Gnome::Glib::N-Error result of a task function.

return-error-if-cancelled

Checks if $task's Gnome::Gio::Cancellable has been cancelled, and if so, sets $task's error accordingly and completes the task (see .return-pointer() for more discussion of exactly what this means).

method return-error-if-cancelled (--> Bool )

Return value; True if $task has been cancelled, False if not.

return-int

Sets $task's result to $result and completes the task (see .return-pointer() for more discussion of exactly what this means).

method return-int ( Int() $result )
  • $result; the integer (#gssize) result of a task function..

return-new-error This function is not yet available

Sets $task's result to a new Gnome::Glib::N-Error created from $domain, $code, $format, and the remaining arguments, and completes the task (see .return-pointer() for more discussion of exactly what this means).

See also .return-error().

method return-new-error ( UInt $domain, Int() $code, Str $format, … )
  • $domain; a Gnome::Glib::Task..

  • $code; an error code..

  • $format; a string with format characters..

  • …; …. Note that each argument must be specified as a type followed by its value!

return-new-error-literal

Sets $task’s result to a new [type $GLib.Error] created from $domain, $code, $message and completes the task.

See .return-pointer() for more discussion of exactly what ‘completing the task’ means.

See also .return-new-error().

method return-new-error-literal ( UInt $domain, Int() $code, Str $message )
  • $domain; a Gnome::Glib::Task..

  • $code; an error code..

  • $message; an error message.

return-pointer

Sets $task's result to $result and completes the task. If $result is defined, then $result-destroy will be used to free $result if the caller does not take ownership of it with .propagate-pointer().

"Completes the task" means that for an ordinary asynchronous task it will either invoke the task's callback, or else queue that callback to be invoked in the proper Gnome::Glib::N-MainContext, or in the next iteration of the current Gnome::Glib::N-MainContext. For a task run via .run-in-thread() or .run-in-thread-sync(), calling this method will save $result to be returned to the caller later, but the task will not actually be completed until the Gnome::Gio::T-task exits.

Note that since the task may be completed before returning from .return-pointer(), you cannot assume that $result is still valid after calling this, unless you are still holding another reference on it.

method return-pointer ( gpointer $result, GDestroyNotify &result-destroy )
  • $result; (transfer ownership: full) the pointer result of a task function.

  • GDestroyNotify &result-destroy; a Gnome::Glib::T-types function.. The function must be specified with the following signature; :( gpointer $data ).

return-prefixed-error This function is not yet available

Sets $task's result to $error (which $task assumes ownership of), with the message prefixed according to $format, and completes the task (see .return-pointer() for more discussion of exactly what this means).

Note that since the task takes ownership of $error, and since the task may be completed before returning from .return-prefixed-error(), you cannot assume that $error is still valid after calling this. Call g_error_copy() on the error if you need to keep a local copy as well.

See also .return-error(), g_prefix_error().

method return-prefixed-error ( N-Object $error, Str $format, … )
  • $error; (transfer ownership: full) the Gnome::Glib::N-Error result of a task function.

  • $format; a string with format characters..

  • …; …. Note that each argument must be specified as a type followed by its value!

return-value

Sets $task's result to $result (by copying it) and completes the task.

If $result is undefined then a Gnome::GObject::N-Value of type G_TYPE_POINTER with a value of undefined will be used for the result.

This is a very generic low-level method intended primarily for use by language bindings; for C code, .return-pointer() and the like will normally be much easier to use.

method return-value ( N-Object $result )
  • $result; the Gnome::GObject::N-Value result of a task function

run-in-thread

Runs $task-func in another thread. When $task-func returns, $task's Gnome::Gio::T-iotypes will be invoked in $task's Gnome::Glib::N-MainContext.

This takes a ref on $task until the task completes.

See Gnome::Gio::T-task for more details about how $task-func is handled.

Although GLib currently rate-limits the tasks queued via .run-in-thread(), you should not assume that it will always do this. If you have a very large number of tasks to run (several tens of tasks), but don't want them to all run at once, you should only queue a limited number of them (around ten) at a time.

Be aware that if your task depends on other tasks to complete, use of this function could lead to a livelock if the other tasks also use this function and enough of them (around 10) execute in a dependency chain, as that will exhaust the thread pool. If this situation is possible, consider using a separate worker thread or thread pool explicitly, rather than using .run-in-thread().

method run-in-thread ( GTaskThreadFunc &task-func )
  • GTaskThreadFunc &task-func; a Gnome::Gio::T-task. The function must be specified with the following signature; :( N-Object $task, gpointer $source-object, gpointer $task-data, N-Object $cancellable ).

run-in-thread-sync

Runs $task-func in another thread, and waits for it to return or be cancelled. You can use .propagate-pointer(), etc, afterward to get the result of $task-func.

See Gnome::Gio::T-task for more details about how $task-func is handled.

Normally this is used with tasks created with a undefined callback, but note that even if the task does have a callback, it will not be invoked when $task-func returns. Gnome::Gio::Task:completed will be set to True just before this function returns.

Although GLib currently rate-limits the tasks queued via .run-in-thread-sync(), you should not assume that it will always do this. If you have a very large number of tasks to run, but don't want them to all run at once, you should only queue a limited number of them at a time.

method run-in-thread-sync ( GTaskThreadFunc &task-func )
  • GTaskThreadFunc &task-func; a Gnome::Gio::T-task. The function must be specified with the following signature; :( N-Object $task, gpointer $source-object, gpointer $task-data, N-Object $cancellable ).

set-check-cancellable

Sets or clears $task's check-cancellable flag. If this is True (the default), then .propagate-pointer(), etc, and .had-error() will check the task's Gnome::Gio::Cancellable first, and if it has been cancelled, then they will consider the task to have returned an "Operation was cancelled" error (G_IO_ERROR_CANCELLED), regardless of any other error or return value the task may have had.

If $check-cancellable is False, then the Gnome::Gio::Task will not check the cancellable itself, and it is up to $task's owner to do this (eg, via .return-error-if-cancelled()).

If you are using .set-return-on-cancel() as well, then you must leave check-cancellable set True.

method set-check-cancellable ( Bool() $check-cancellable )
  • $check-cancellable; whether Gnome::Gio::Task will check the state of its Gnome::Gio::Cancellable for you..

set-name

Sets $task’s name, used in debugging and profiling. The name defaults to undefined.

The task name should describe in a human readable way what the task does. For example, ‘Open file’ or ‘Connect to network host’. It is used to set the name of the Gnome::Glib::N-Source used for idle completion of the task.

This function may only be called before the $task is first used in a thread other than the one it was constructed in. It is called automatically by .set-source-tag() if not called already.

method set-name ( Str $name )
  • $name; a human readable name for the task, or undefined to unset it.

set-priority

Sets $task's priority. If you do not call this, it will default to G_PRIORITY_DEFAULT.

This will affect the priority of GSources created with .attach-source() and the scheduling of tasks run in threads, and can also be explicitly retrieved later via .get-priority().

method set-priority ( Int() $priority )
  • $priority; the [priority](iface.AsyncResult.html#io-priority) of the request.

set-return-on-cancel

Sets or clears $task's return-on-cancel flag. This is only meaningful for tasks run via .run-in-thread() or .run-in-thread-sync().

If $return-on-cancel is True, then cancelling $task's Gnome::Gio::Cancellable will immediately cause it to return, as though the task's Gnome::Gio::T-task had called .return-error-if-cancelled() and then returned.

This allows you to create a cancellable wrapper around an uninterruptible function. The Gnome::Gio::T-task just needs to be careful that it does not modify any externally-visible state after it has been cancelled. To do that, the thread should call .set-return-on-cancel() again to (atomically) set return-on-cancel False before making externally-visible changes; if the task gets cancelled before the return-on-cancel flag could be changed, .set-return-on-cancel() will indicate this by returning False.

You can disable and re-enable this flag multiple times if you wish. If the task's Gnome::Gio::Cancellable is cancelled while return-on-cancel is False, then calling .set-return-on-cancel() to set it True again will cause the task to be cancelled at that point.

If the task's Gnome::Gio::Cancellable is already cancelled before you call .run-in-thread()/.run-in-thread-sync(), then the Gnome::Gio::T-task will still be run (for consistency), but the task will also be completed right away.

method set-return-on-cancel ( Bool() $return-on-cancel --> Bool )
  • $return-on-cancel; whether the task returns automatically when it is cancelled..

Return value; True if $task's return-on-cancel flag was changed to match $return-on-cancel. False if $task has already been cancelled..

set-source-tag

Sets $task's source tag.

You can use this to tag a task return value with a particular pointer (usually a pointer to the function doing the tagging) and then later check it using .get-source-tag() (or g_async_result_is_tagged()) in the task's "finish" function, to figure out if the response came from a particular place.

A macro wrapper around this function will automatically set the task’s name to the string form of $source-tag if it’s not already set, for convenience.

method set-source-tag ( gpointer $source-tag )
  • $source-tag; an opaque pointer indicating the source of this task.

set-static-name

Sets $task’s name, used in debugging and profiling.

This is a variant of .set-name() that avoids copying $name.

method set-static-name ( Str $name )
  • $name; a human readable name for the task. Must be a string literal.

set-task-data

Sets $task's task data (freeing the existing task data, if any).

method set-task-data ( gpointer $task-data, GDestroyNotify &task-data-destroy )
  • $task-data; task-specific data.

  • GDestroyNotify &task-data-destroy; Gnome::Glib::T-types for $task-data. The function must be specified with the following signature; :( gpointer $data ).

Functions

is-valid

Checks that $result is a Gnome::Gio::Task, and that $source-object is its source object (or that $source-object is undefined and $result has no source object). This can be used in g_return_if_fail() checks.

method is-valid ( gpointer $result, gpointer $source-object --> Bool )
  • $result; A Gnome::Gio::R-AsyncResult.

  • $source-object; the source object expected to be associated with the task.

Return value; True if $result and $source-object are valid, False if not.

report-error

Creates a Gnome::Gio::Task and then immediately calls .return-error() on it. Use this in the wrapper function of an asynchronous method when you want to avoid even calling the virtual method. You can then use g_async_result_is_tagged() in the finish method wrapper to check if the result there is tagged as having been created by the wrapper method, and deal with it appropriately if so.

See also .report-new-error().

method report-error ( gpointer $source-object, GAsyncReadyCallback &callback, gpointer $callback-data, gpointer $source-tag, N-Object $error )
  • $source-object; the Gnome::GObject::Object that owns this task, or undefined..

  • GAsyncReadyCallback &callback; a Gnome::Gio::T-iotypes.. The function must be specified with the following signature; :( N-Object $source-object, N-Object $res, gpointer $data ).

  • $callback-data; user data passed to $callback..

  • $source-tag; an opaque pointer indicating the source of this task.

  • $error; (transfer ownership: full) error to report

report-new-error This function is not yet available

Creates a Gnome::Gio::Task and then immediately calls .return-new-error() on it. Use this in the wrapper function of an asynchronous method when you want to avoid even calling the virtual method. You can then use g_async_result_is_tagged() in the finish method wrapper to check if the result there is tagged as having been created by the wrapper method, and deal with it appropriately if so.

See also .report-error().

method report-new-error ( gpointer $source-object, GAsyncReadyCallback &callback, gpointer $callback-data, gpointer $source-tag, UInt $domain, Int() $code, Str $format, … )
  • $source-object; the Gnome::GObject::Object that owns this task, or undefined..

  • GAsyncReadyCallback &callback; a Gnome::Gio::T-iotypes.. The function must be specified with the following signature; :( N-Object $source-object, N-Object $res, gpointer $data ).

  • $callback-data; user data passed to $callback..

  • $source-tag; an opaque pointer indicating the source of this task.

  • $domain; a Gnome::Glib::Task..

  • $code; an error code..

  • $format; a string with format characters..

  • …; …. Note that each argument must be specified as a type followed by its value!