BackgroundWorker

class compas_eve.ghpython.BackgroundWorker[source]

Bases: object

Background worker simplifies the creation of long-running tasks inside Grasshopper.

A long-running task is any piece of code that will run for an extended period of time, for example, a very complex calculation, or loading a very large data file, etc.

To use it, write your long-running function in a Grasshopper GHPython component, and pass it as the input to the background worker component. The worker will continue working without blocking the UI.

The following is an example of a long-running function that updates the progress while it runs.

import time

def do_something_long_and_complicated(worker):
    # Result can be of any data type
    result = 0

    for i in range(50):
        worker.current_value = i
        result += i
        worker.display_progress(i / (50-1))
        time.sleep(0.01)

    worker.display_message("Done!")

    return result
Parameters:
ghenvGhPython.Component.PythonEnvironment

Grasshopper environment object

long_running_functionfunction, optional

This function will be the main entry point for the long-running task.

dispose_functionfunction, optional

If defined, this function will be called when the worker is disposed. It can be used for clean-up tasks and resource deallocation.

auto_set_donebool, optional

If true, the worker state will be automatically set to Done after the function returns. Defaults to True.

argstuple, optional

List or tuple of arguments for the invocation of the long_running_function. Defaults to ().

Methods

display_message

Display a message in the component without triggering a solution expiration.

display_progress

Display a progress indicator in the component.

dispose

Invoked when the worker is being disposed.

has_requested_cancellation

instance_by_component

Get the worker instance assigned to the component.

is_done

Indicate whether the worker is done or not.

is_working

Indicate whether the worker is currently working or not.

request_cancellation

Mark the current worker as cancelled, so that the background task can stop processing.

set_internal_state_to_cancelled

Set the internal state to cancelled.

set_internal_state_to_done

Set the internal state to done, which indicates the worker has completed.

set_internal_state_to_working

Set the internal state to working.

start_work

Start the background processing thread where work will be performed.

stop_instance_by_component

Stops the worker instance assigned to the component.

update_result

Update the result of the worker.