Recursive AI

Wake a native event loop from a background thread in C#

OnePlatform is a free, open-source library for windows, input, clipboard, displays and gamepads in .NET from Recursive AI. MIT or Apache-2.0, no native DLLs to ship.

Queue the worker’s result, then call Wake() so the event-loop thread can handle it without polling.

Terminal
dotnet add package RecursiveAI.OnePlatform

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OnePlatform;
using System.Collections.Concurrent;
using System.Threading.Tasks;
 
using var app = PlatformApp.Create();
var jobs = new ConcurrentQueue<string>();
var worker = Task.Run(() =>
{
    jobs.Enqueue("Result ready.");
    app.Wake();
});
string? result;
do
{
    app.PumpEvents(10_000);
    while (app.TryGetEvent(out _)) { }
} while (!jobs.TryDequeue(out result));
worker.GetAwaiter().GetResult();
System.Console.WriteLine(result);

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

The main thread prints the result:

Text
Result ready.

The full program

The example uses a standalone worker thread and delays the result briefly so the main thread has time to enter PumpEvents. It doesn’t open a window. On a Linux desktop with X11, it can use the X11 event loop even without creating a window.

C#
using System;
using System.Collections.Concurrent;
using System.Threading;
using OnePlatform;
 
using var app = PlatformApp.Create();
var jobs = new ConcurrentQueue<string>();
var worker = new Thread(() =>
{
    Thread.Sleep(200); // Simulate work arriving later.
    jobs.Enqueue("Worker result received on the main thread.");
    app.Wake();
});
worker.Start();
 
while (true)
{
    app.PumpEvents(10_000);
    while (app.TryGetEvent(out _)) { }
    if (jobs.TryDequeue(out var job))
    {
        Console.WriteLine(job);
        break;
    }
}
worker.Join();
Text
Worker result received on the main thread.

A wake doesn’t produce a PlatformEvent, so don’t wait for a matching event kind. In this demo native events are discarded; in a windowed app, handle them in the inner loop and check your work queue even when there were no native events.

Variations

To try the same wake-and-queue code without a display server, replace the PlatformApp.Create() line in the full program:

C#
using var app = PlatformApp.Create(new()
{
    Backend = PlatformBackendKind.Headless
});

The headless backend also wakes a blocking wait. It prints Worker result received on the main thread.

The short answer

Use a thread-safe queue for the worker’s data and PlatformApp.Wake() for the signal. In that order: publish the result, then signal the wait. Wake() is safe to call from the worker; it makes PumpEvents return without waiting for another user action or for its timeout to expire. Read the queue on the thread running the event loop. The signal doesn’t carry the result, and it doesn’t run your handler on the worker’s thread.

How do I wake a waiting thread without polling?

For a thread already waiting inside PumpEvents, signal that wait rather than adding a second wait or shortening the timeout. On X11 and Wayland, OnePlatform waits on both the display connection and a wake pipe. On Windows it waits on both the message queue and a wake event. Either native input or a worker can therefore bring the main thread back to the same loop. If you replace the native wait with a blocking read from your own queue on that thread, the loop won’t process window input while it waits for a job. The long timeout in this example is a backstop, not a polling interval for the worker’s result.

The headless backend also supports waking a timed wait. The browser and iOS backends don’t block in PumpEvents, so Wake() has no effect there. See the backend table before using this pattern as part of a shared desktop and browser loop.

How do I pass data from a background thread to the main thread?

Don’t count wakes. If the worker signals before the main thread enters the wait, the next wait returns early. If several calls pile up, the library can combine them into one early return. The queue, not the number of times PumpEvents returns, tells you how much work is pending. Drain it after each return in a persistent loop; if you take only one item and then wait again, other items from the same burst may still be queued with no wake left. If you wake before enqueuing, the main thread can see an empty queue and go back to sleep before the result arrives.

All oneplatform recipes