A BackgroundWorker allows the execution of a function on a background thread, avoiding the blocking of the main thread. This is particularly useful for long-running operations like file I/O, network requests, or computationally intensive tasks.

Notes:

  • Thread Support: Only system targets (such as C++, Neko) support threading.
  • Events: The class uses the Event class to dispatch completion, error, and progress notifications.

See also:

  • ThreadPool for more advanced threading capabilities, including thread safety, HTML5 threads, and more robust handling of tasks.

Constructor

new()

Creates a new BackgroundWorker instance.

Variables

read onlycanceled:Bool

Indicates whether the worker has been canceled.

read onlycompleted:Bool

Indicates whether the worker has completed its task.

@:value(new Event<Dynamic>())doWork:_Event_Dynamic_Void<Dynamic ‑> Void> = new Event<Dynamic>()

Dispatched when the worker is about to perform its task. The function to execute should be added as a listener to this event.

@:value(new Event<Dynamic>())onComplete:_Event_Dynamic_Void<Dynamic ‑> Void> = new Event<Dynamic>()

Dispatched when the worker has successfully completed its task.

@:value(new Event<Dynamic>())onError:_Event_Dynamic_Void<Dynamic ‑> Void> = new Event<Dynamic>()

Dispatched if an error occurs during the execution of the worker's task.

@:value(new Event<Dynamic>())onProgress:_Event_Dynamic_Void<Dynamic ‑> Void> = new Event<Dynamic>()

Dispatched periodically during the worker's task to provide progress updates.

Methods

cancel():Void

Cancels the worker's task if it is still running. This won't stop the thread immediately.

@:value({ message : null })run(?message:Dynamic):Void

Starts the worker's task, optionally passing a message to the task.

Parameters:

message

An optional message to pass to the worker's task.

@:value({ message : null })sendComplete(?message:Dynamic):Void

Sends a completion message, indicating that the worker has finished its task.

Parameters:

message

An optional message to pass to the onComplete event.

@:value({ message : null })sendError(?message:Dynamic):Void

Sends an error message, indicating that an error occurred during the worker's task.

Parameters:

message

An optional message to pass to the onError event.

@:value({ message : null })sendProgress(?message:Dynamic):Void

Sends a progress update message.

Parameters:

message

An optional message to pass to the onProgress event.