Skip to content

9. Message queue πŸ“¬

Artyom M. edited this page Nov 5, 2026 · 5 revisions

Message Queue

Package: Scarlet.DirectN.Threading (installed with the main library)

DirectNMessageQueue and DirectNSynchronizationContext are what the host uses to run work on the UI thread. Applications normally use them through the host's DirectNDispatcher (IDirectNThread.Dispatcher, also registered in the container), IDirectNThread.SynchronizationContext or JoinableTaskFactory; this page describes the guarantees, and how to use the queue directly on a thread you run yourself.

How It Works

Work is kept in memory and a single wake-up message is posted to a message-only window of the UI thread. Window messages are dispatched by every message loop, including modal ones (menus, message boxes, task dialogs, window move/resize), so queued work never stalls while one of those is open. Thread messages (PostThreadMessage) would be lost there.

At most 256 items, and no new item after about 15 ms (a frame), run per wake-up; a single long item can't be interrupted. When more are queued and input, paint or timer messages are pending, the queue continues from a timer (retrieved after all of them, as WPF does for background work), so a flood of posts can't starve them.

There is at most one queue per thread, so everything on a UI thread shares the same ordering, exception path and SynchronizationContext.

Guarantees

  • Post runs the work on the UI thread in the order posted. TryPost returns false (and Post throws InvalidOperationException) only when the work can never run: the queue is closed or its thread has exited (IsClosed). A full thread message queue is retried, not reported. Posting through DirectNSynchronizationContext never throws: once the queue is closed the work is dropped, like WPF's and WinForms' contexts after shutdown (it is the context await resumes on, and an exception there would terminate the process). DroppedCount counts the work dropped by closing.
  • Send from another thread returns once the work ran (its exception, if any, is rethrown to the caller), or throws InvalidOperationException because the queue closed or its thread exited first, also when the thread exits without closing the queue. Like any Send, it waits as long as the UI thread is alive but doesn't process messages (blocked, or busy in a long callback). On the UI thread, Send runs inline.
  • No capacity limit: the queue accepts any amount of work; don't flood the UI thread with unbounded work.
  • ExecutionContext: like WPF's Dispatcher and WinForms' BeginInvoke, each item runs in the ExecutionContext captured from its caller (AsyncLocal values, culture), and what it changes there doesn't leak into later items. Work posted with flow suppressed runs in the UI thread's own baseline context.
  • Exceptions from queued work raise UnhandledException; unless Handled is set, they are rethrown on the thread pool and terminate the process, like WinForms and WPF.

Dispatcher: Post and InvokeAsync

DirectNDispatcher is the Action-based API for scheduling UI work. DirectNMessageQueue is one; the host's is IDirectNThread.Dispatcher, also injectable as DirectNDispatcher:

public sealed class StatusService(DirectNDispatcher dispatcher, MainWindowHolder holder)
{
    public void ShowStatus(string text) => dispatcher.Post(() => holder.Window!.Text = text);

    public Task<string> ReadTitleAsync(CancellationToken cancellationToken) =>
        dispatcher.InvokeAsync(() => holder.Window!.Text, cancellationToken);
}
  • Post(Action) / TryPost(Action): fire and forget, with the queue's guarantees above. Exceptions go to the UI thread's unhandled-exception path.
  • InvokeAsync: queues the callback and returns a task that completes when it has run, with its result (Func<T>), or when an asynchronous callback (Func<Task>, Func<Task<T>>) has fully completed. The callback's exception faults the task instead of raising UnhandledException.
    • Cancellation only prevents the callback from starting; once started, the callback owns its cancellation.
    • Work that can't run faults the task with InvalidOperationException: rejected because the dispatcher no longer accepts work, or dropped because the queue closed or its thread exited before it ran. A task never stays pending because the UI thread went away.
    • Always queued, also when called on the UI thread, so the callback never runs inline. Never block on the task on the UI thread (.Wait(), .Result): it deadlocks.
    • An asynchronous callback needs the message loop running until it completes, to resume its UI continuations; shutdown doesn't force it to complete.
  • CheckAccess() / VerifyAccess(): whether the calling thread is the UI thread; VerifyAccess throws InvalidOperationException when it isn't.

Like the queue, every callback runs in its caller's ExecutionContext.

DirectNDispatcher is abstract: a test can subclass it (implement CheckAccess and TryEnqueue) and register the fake before AddDirectN(), which keeps an existing registration.

Through the Host

IDirectNThread.Dispatcher and IDirectNThread.SynchronizationContext build on the queue and add the host's lifetime:

  • The dispatcher's Post, TryPost and InvokeAsync work before the UI thread exists: work is kept and runs once the application has started. If the application never starts (startup fails or the host is disposed first), kept invocations fault with InvalidOperationException. After the UI thread has ended, TryPost returns false, Post throws InvalidOperationException, and InvokeAsync returns a faulted task. As with SwitchToMainThreadAsync, don't await an invocation in a hosted service's StartAsync: the UI thread starts after it, so startup would hang.

For the synchronization context:

  • Post works at any time and never throws: before the UI thread exists, work is kept and runs once the application has started (in the poster's ExecutionContext); after it ended, work is dropped and logged.
  • Send throws InvalidOperationException before the UI thread exists, instead of blocking: a Send from a hosted service's StartAsync would otherwise deadlock, since the UI thread starts after it. While the UI thread runs, it has the queue's guarantee.

Like any Send, calling it from a thread the UI thread is waiting on deadlocks.

Using the Queue Directly

On a thread that runs a message loop:

var queue = DirectNMessageQueue.GetOrCreateForCurrentThread();
SynchronizationContext.SetSynchronizationContext(queue.SynchronizationContext);
queue.UnhandledException += (_, e) => { Log(e.Exception); e.Handled = true; };

// ... run the message loop ...

queue.Close();

From any thread:

queue.Post(_ => window.Text = "Updated", null);

Call Close() on the owning thread when its message loop has ended for good (the host does this): it drops queued work, fails pending Send calls, rejects later posts, and releases the window and native handle. A queue whose thread exits without Close is still released by the garbage collector.

API

Member Description
DirectNMessageQueue.GetOrCreateForCurrentThread() The queue of the calling thread, created on first use
DirectNMessageQueue.Current The queue of the calling thread, or null
Post / TryPost Queue work for the UI thread (Action, or SendOrPostCallback and state)
TryPost(callback, state, onAbandoned) Queue work, and be told if it is dropped without running (the queue closes or its thread exits first). Exactly one of callback and onAbandoned runs for accepted work; onAbandoned may run before TryPost returns, also when it returns false
InvokeAsync Await an action, result, or asynchronous callback on the UI thread
Close() Owner thread only: drops queued work, rejects later posts, releases the window and native handle
IsClosed Whether the queue no longer accepts work
CheckAccess(), VerifyAccess(), Thread, ManagedThreadId The owning thread
SynchronizationContext The DirectNSynchronizationContext posting to this queue
UnhandledException Exceptions from queued work
RethrowAsUnhandled(exception) Surfaces an exception as unhandled without crossing a native callback boundary

Clone this wiki locally