Skip to content

EN CSharp Cancellation

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Cancel, pause and background scripts

Manual C# · Examples UO

CancellationTokenSource creates a cancellation request, CancellationToken is passed to the operation. Cancellation is cooperative: the operation verifies the token or passes it on. The embedded script gets Cancellation; WaitAsync is used for waiting.

Simple example (Example.csx)

Save this example separately as Example.csx. Run it independently of the other examples on this page.

Example.csx:

Cancellation.ThrowIfCancellationRequested();
await WaitAsync(10);
UO.Print("Done");

Cancellation is cooperative: the token check and WaitAsync respond to Stop; third-party code without cancellation support may continue running.

Result:

Done
for (int i = 0; i < 3; i++)
{
    Cancellation.ThrowIfCancellationRequested();
    await WaitAsync(100);
    UO.Print($"Tick {i}");
}
{
    using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
    using var linked = CancellationTokenSource.CreateLinkedTokenSource(Cancellation, timeout.Token);
    try
    {
        await Task.Delay(10, linked.Token);
        UO.Print("Operation completed");
    }
    catch (OperationCanceledException) when (timeout.IsCancellationRequested)
    {
        UO.Print("Local timeout");
    }
}

Do not replace stopping the script with an infinite interception OperationCanceledException. An arbitrary blocking call to a third-party library does not become interruptible just because of the presence of a token. Pausing and asking to cancel have different purposes: pause preserves continuation, cancel terminates execution.

Official Documentation: Cancel, Pause, and Background Scripts - Microsoft Learn.

The cancellation request is cooperative. Task.Delay without Cancellation transfer, waiting for third-party task and library call without cancel support can continue after pressing Stop. Once a cancellation request is made, further gaming activities of that execution are prohibited; this does not force any .NET code to terminate immediately.

Clone this wiki locally