menu_bookDocumentation
MainThread.Queue: Running Code on the Main Thread from Worker Threads
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 threadFrame-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:- During FrameStart (twice — before and after game tick)
- During FrameEnd
Was this helpful?