menu_bookDocumentation

MainThread.Queue: Running Code on the Main Thread from Worker Threads

calendar_today May 4, 2026 schedule ~1 min read person patrickjr verified 50

MainThread.Queue: Running Code on the Main Thread from Worker Threads

s&box is single-threaded for game logic. If you have code running on a worker thread (e.g., in a Task or WorkerThread) that needs to interact with the scene, you must marshal it back to the main thread.

MainThread.Queue

CSHARP
// Queue an action to run on the main thread
// If already on the main thread, runs immediately and synchronously
MainThread.Queue( () =>
{
    // Safe to access scene, GameObjects, components here
    someGameObject.Destroy();
} );

MainThread.Wait (async)

CSHARP
// In an async method, await the main thread
await MainThread.Wait();

// Now on the main thread
someComponent.Enabled = false;

Checking the Main Thread

CSHARP
ThreadSafe.IsMainThread  // true if on the main thread
ThreadSafe.AssertIsMainThread(); // throws if not on main thread

Frame-End Disposables

Objects that need to be disposed after rendering (e.g., render targets) can be queued for end-of-frame disposal:
CSHARP
// Dispose after the current frame finishes rendering
EngineLoop.DisposeAtFrameEnd( myDisposable );

When MainThread.Queue Runs

MainThread.Queue actions are drained in EngineLoop.RunAsyncTasks(), which is called multiple times per frame: This means queued actions run within the same frame they were queued, not the next frame.
Was this helpful?