Recursive AI

Schedule a delayed UI state update in C#

OneUI is a free, open-source .NET library from Recursive AI for writing UI components in HTML, CSS, and C# that run in native windows on desktops and phones, or in a browser via WebAssembly, with OneApp. MIT or Apache-2.0, no native dependencies.

Start a timer when the notice component appears. Removing the notice cancels the timer.

Terminal
dotnet add package RecursiveAI.OneUI

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

Notice.cs calls SetTimeout from OnMounted:

C#
using System;
using OneUI.Components;
 
public partial class Notice
{
    protected override void OnMounted() =>
        SetTimeout(TimeSpan.FromSeconds(1),
            () => Ready = true);
 
    [State]
    public partial bool Ready { get; set; }
}

The example is the full program below: unzip it and dotnet run.

Prints <p>Waiting</p> before the timeout and <p>Ready</p> after it.

The full program

To build by hand, run dotnet new console with the .NET 10 SDK, then run the install command above. Save Notice.cs and the Notice.html template next to your project file. OneUI generates the Ready property and binds it to the displayed text:

HTML
<p>{Ready ? "Ready" : "Waiting"}</p>

The download pins OneUI 1.1.0. Replace the starter Program.cs with the code below. It uses an in-memory document and a ManualScheduler, a clock you advance in code. The first notice stays mounted until its timeout fires; the second is removed before its timeout is due.

C#
using OneUI.Components;
using OneUI.Components.Reference;
 
var doc = new ReferenceDocument();
var clock = new ManualScheduler();
var ui = new UiContext(doc);
ui.Scheduler = clock;
 
var first = ui.Mount(new Notice());
Console.WriteLine(doc.ToHtml());
clock.Advance(TimeSpan.FromSeconds(1));
Console.WriteLine(doc.ToHtml());
ui.Unmount(first);
 
var second = ui.Mount(new Notice());
Console.WriteLine(
    "Pending before unmount: " +
    clock.PendingCount);
ui.Unmount(second);
Console.WriteLine(
    "Pending after unmount: " +
    clock.PendingCount);
clock.Advance(TimeSpan.FromSeconds(1));
Console.WriteLine(
    $"Removed notice updated: {second.Ready}");
Text
<p>Waiting</p>
<p>Ready</p>
Pending before unmount: 1
Pending after unmount: 0
Removed notice updated: False

If the host hasn’t assigned UiContext.Scheduler, scheduling a timer throws InvalidOperationException. Check ui.HasScheduler when working with a context whose host you don’t control.

Variations

For a repeating status indicator, replace the call in OnMounted with this interval. Each tick flips the same Ready property until the component is removed:

C#
SetInterval(TimeSpan.FromSeconds(1),
    () => Ready = !Ready);

The short answer

Inside a mounted OneUI component, call the protected SetTimeout(delay, callback) and update a [State] property in the callback. OneUI runs the callback as a batch and updates the bindings that depend on the changed state. If the component leaves the tree first, OneUI cancels the timeout.

How do you run a timer on the UI thread in C#?

In OneUI, the host supplies an IUiScheduler through UiContext.Scheduler. Its Schedule method calls back once on the UI thread and returns a handle that cancels the scheduled work. The component’s timer uses that scheduler, so the callback can set Ready directly. If a callback sets several properties, the dirty bindings are recomputed at the end of the batch, rather than after each assignment.

Choose OnMounted for a delay that starts when the component appears. That hook runs after the creation changes commit. Start the timer from an event handler instead if it should wait for a user action. The example advances a manual clock: it exercises the same component callback and cancellation without making the console program wait a real second. For real elapsed time in a native OneApp window, AppHost supplies HostScheduler, which posts timer callbacks to the app’s UI thread. OneApp’s component host assigns it before mounting your component:

C#
Context = new UiContext(this)
    { Scheduler = scheduler };

That assignment is inside OneApp; app code doesn’t need to set a scheduler. In the browser, OneApp’s browser host supplies its own scheduler backed by setTimeout.

How do you cancel a UI timer when a component is removed?

Use the component’s protected timer methods, not Context.SetTimeout or Context.SetInterval, for work that belongs to that component. The protected methods track their handles and cancel pending calls on removal. To cancel while the component is still mounted, keep the IDisposable returned by the timer and dispose it when the work is no longer needed. For example, if a user can dismiss an inline message before its auto-dismiss fires, the dismissal can cancel the existing timer rather than leaving work queued.

Use SetTimeout when you want one change, and SetInterval when you want repeated changes. An interval re-arms after it fires instead of queueing ticks for a callback that is taking longer than the interval. The change-set docs describe both methods and the manual scheduler.

All oneui recipes