For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt, and this page is available as Markdown at /next/api/lynx-native-api/lynx-extension-module/post-task-to-runtime.md.
Lynx
  • English
  • PostTaskToRuntime

    The PostTaskToRuntime method provides a way to schedule a task for execution on the BTS (Background Thread Script) thread. This is the primary mechanism for safely dispatching work from any thread (like the UI thread) to the thread where the JavaScript runtime lives.

    It is essential for any operation that needs to interact with N-API or other BTS-thread-specific resources from outside the BTS thread. The method has overloads for both C++ std::function and C-style function pointers.

    Method Signature

    With std::function task

    void PostTaskToRuntime(std::function<void()> task);

    With C-function task

    void PostTaskToRuntime(lynx_extension_module_post_task_func func,
                           void* user_data);

    Parameters

    NameTypeDescriptionRequired
    taskstd::function<void()>A C++ function object (like a lambda) to be executed on the BTS thread.Yes
    funclynx_extension_module_post_task_funcA C-style function pointer to be executed on the BTS thread.Yes
    user_datavoid*(C-function overload only) A pass-through context pointer for the C-function task. Pass nullptr when no context is needed.Yes

    Usage

    Use this method whenever you need to perform an action on the BTS thread from another thread. A common scenario is responding to a UI event by updating state in the JavaScript runtime.

    Example

    #include "lynx_extension_module.h"
    
    class MyExtensionModule : public lynx::pub::LynxExtensionModule {
    public:
        // This method might be called from the UI thread in response to a user action
        void OnUserClickedButton() {
            printf("Button clicked on UI thread. Posting task to BTS thread...\\n");
    
            PostTaskToRuntime([]() {
                // This code will execute safely on the BTS thread.
                printf("Task is now running on the BTS thread.\\n");
                // You can safely call N-API functions or interact with runtime state here.
            });
        }
    
        // ... other methods
    };

    See Also

    Compatibility

    LCD tables only load in the browser

    Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the Apache License 2.0.