Repository navigation
9. 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.
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.
-
Post runs the work on the UI thread in the order posted.
TryPostreturnsfalse(andPostthrowsInvalidOperationException) 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 throughDirectNSynchronizationContextnever throws: once the queue is closed the work is dropped, like WPF's and WinForms' contexts after shutdown (it is the contextawaitresumes on, and an exception there would terminate the process).DroppedCountcounts 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
InvalidOperationExceptionbecause the queue closed or its thread exited first, also when the thread exits without closing the queue. Like anySend, 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,Sendruns 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 theExecutionContextcaptured from its caller (AsyncLocalvalues, 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; unlessHandledis set, they are rethrown on the thread pool and terminate the process, like WinForms and WPF.
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 raisingUnhandledException.- 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;VerifyAccessthrowsInvalidOperationExceptionwhen 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.
IDirectNThread.Dispatcher and IDirectNThread.SynchronizationContext build on the queue and add the host's lifetime:
- The dispatcher's
Post,TryPostandInvokeAsyncwork 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 withInvalidOperationException. After the UI thread has ended,TryPostreturnsfalse,PostthrowsInvalidOperationException, andInvokeAsyncreturns a faulted task. As withSwitchToMainThreadAsync, don't await an invocation in a hosted service'sStartAsync: the UI thread starts after it, so startup would hang.
For the synchronization context:
-
Postworks at any time and never throws: before the UI thread exists, work is kept and runs once the application has started (in the poster'sExecutionContext); after it ended, work is dropped and logged. -
SendthrowsInvalidOperationExceptionbefore the UI thread exists, instead of blocking: aSendfrom a hosted service'sStartAsyncwould 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.
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.
| 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 |
Scarlet.Extensions.Hosting.DirectN
Getting Started
Core Features
Extensions
Reference