Skip to content

Add CancellationToken support to SuspendBridge - #137

Merged
jonathanpeppers merged 4 commits into
mainfrom
jonathanpeppers/suspend-cancellation-token
Jun 7, 2026
Merged

jonathanpeppers merged 4 commits into
mainfrom
jonathanpeppers/suspend-cancellation-token

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Owner

Compared our hand-rolled Kotlin-suspend → Task plumbing against the workaround in dotnet/android-libraries#1456 and noticed our one real gap: no CancellationToken. This wires it through.

What changes

SuspendBridge.Invoke (both overloads) and the two ScrollState async facades (ScrollToAsync, AnimateScrollToAsync) now take a trailing CancellationToken cancellationToken = default. When the token fires, the returned task transitions to Canceled (OperationCanceledException at the awaiter) via the allocation-free CancellationToken.Register((state, token) => ...) overload calling Tcs.TrySetCanceled(token).

Three secondary cleanups fell out of this:

  • Consolidated lifecycle into IDisposable. Java.Lang.Object already implements IDisposable, and in every code path Kotlin is done with the continuation by the time we clean up (sync-throw, sync-completion, post-ResumeWith single-resume contract). The previous AbandonPin() method is gone; Dispose(bool) is now the single, idempotent cleanup point that releases the GCHandle self-pin, disposes the CancellationTokenRegistration, and lets the base call release the JNI peer. Guarded by Interlocked.Exchange(ref _disposed, true).
  • Replaced the ContinueWith tail with a small async Task<T> AwaitAndUnbox(...) helper. A cancelled TCS now surfaces as a Canceled (not Faulted) task because the async state machine routes the uncaught OperationCanceledException straight into AsyncTaskMethodBuilder.SetCanceled.
  • Fixed a pre-existing leak. The sync-completion path used to set the TCS without ever freeing the GCHandle self-pin. The new cont.Dispose() call on that path closes it.

Cancellation semantics (intentional, documented)

This is the "simple" / #1456-shaped cancel: the awaiter sees OperationCanceledException immediately, but the Kotlin suspend body continues to its natural completion. We don't yet wire a Job into SuspendContinuation.Context, so there is no Kotlin-side cancel. When Kotlin eventually resumes, CompleteWithLocalHandle sees the TCS is already completed and disposes the boxed result silently.

True Kotlin-side cancel (calling job.cancel() so animation/scroll bodies stop at the next suspend point) needs JNI bridges for JobKt.Job() + CoroutineContext.plus() + Job.cancel() plus Result.Failure(CancellationException) routing. Left as a follow-up; called out in the SuspendBridge XML doc and in the suspend section of .github/copilot-instructions.md (which also has the updated facade template).

Verification

  • ComposeNet.Compose and ComposeNet.Sample build clean (0 warnings, 0 errors).
  • ComposeNet.SourceGenerators.Tests: 105/105 passing.
  • A post-Register re-check of IsCancellationRequested covers the rare race where the token fires between the pre-check and the registration callback firing synchronously inside the ctor, so we don't start a visible scroll/animation we'd then have to wait on.

jonathanpeppers and others added 3 commits June 7, 2026 14:10
Plumb an optional `CancellationToken cancellationToken = default`
through `SuspendBridge.Invoke` (both overloads), `SuspendContinuation`,
and the `ScrollState.ScrollToAsync` / `AnimateScrollToAsync` facades.

When the token fires the returned task transitions to Canceled
(`OperationCanceledException` at the awaiter) via the allocation-free
`CancellationToken.Register((state, token) => …)` overload calling
`Tcs.TrySetCanceled(token)`. The Kotlin suspend body keeps running to
its natural completion — no `Job` is wired into the coroutine context
yet, so there is no Kotlin-side cancel. When Kotlin eventually
resumes, `CompleteWithLocalHandle` sees the TCS is already completed
and disposes the boxed result without surfacing it. True Kotlin-side
cancel (calling `job.cancel()` so animation/scroll bodies stop at the
next suspend point) is left for a follow-up.

Lifetime cleanup is consolidated into a new idempotent
`SuspendContinuation.ReleaseLifetime(bool disposing = true)` guarded
by an interlocked flag. It replaces `AbandonPin()`, runs from every
completion path (Kotlin resume, sync completion, sync throw,
`Dispose`), and skips the (potentially blocking) CTR dispose when
called from the finalizer thread. This also fixes a pre-existing
sync-completion path leak where the GCHandle self-pin was never
freed if Kotlin returned a result without suspending.

The `ContinueWith` tail in `SuspendBridge.Invoke` is replaced by a
small `async Task<T> AwaitAndUnbox(...)` helper so that a cancelled
TCS naturally surfaces as a Canceled (not Faulted) task via the
async state machine routing the uncaught
`OperationCanceledException` into `AsyncTaskMethodBuilder.SetCanceled`.

A post-`Register` re-check of `IsCancellationRequested` covers the
rare race where cancellation fires between the pre-check and the
registration callback firing synchronously inside the ctor, so we
don't start a visible scroll/animation we'd then have to wait on.

Updates `PublicAPI.Unshipped.txt`, the suspend section of
`.github/copilot-instructions.md` (template + cancellation notes),
and the `ScrollState` XML doc to mention the new parameter and its
awaiter-only semantics.

Co-authored-by: Copilot <[email protected]>
Java.Lang.Object already implements IDisposable, so the previous
ReleaseLifetime / Dispose split was a distinction without a
difference: in every code path Kotlin was already done with the
continuation by the time we ran cleanup (sync-throw never handed it
over, sync-completion already returned a result, post-ResumeWith is
the single-resume contract), so disposing the JNI peer immediately
along with the GCHandle pin and the CTR registration is always safe.

Fold the pin/CTR cleanup into Dispose(bool), guarded by an
interlocked _disposed flag for idempotency, then have the base call
release the JNI peer. ResumeWith and the SuspendBridge sync paths
now just call cont.Dispose() — one method, standard pattern, no
custom lifetime vocabulary.

Co-authored-by: Copilot <[email protected]>
Historical reason for the int: Interlocked.Exchange didn't accept
bool before .NET 9. Since we target net10.0-android we have the
generic overload with the reference-type constraint removed, so
Interlocked.Exchange(ref bool, bool) works directly.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings June 7, 2026 19:17

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds CancellationToken support to the Kotlin suspend-to-C# Task bridging layer (SuspendBridge / SuspendContinuation), addressing a gap compared to the workaround in dotnet/android-libraries#1456. Cancellation is "awaiter-only" — the returned task transitions to Canceled immediately when the token fires, but the underlying Kotlin suspend body runs to natural completion (no Job wired into the coroutine context yet).

Changes:

  • SuspendBridge.Invoke (both overloads) and both ScrollState async facades now accept CancellationToken cancellationToken = default, with a pre-check, post-registration re-check, and allocation-free Register callback that calls TrySetCanceled on the backing TCS.
  • SuspendContinuation lifecycle is consolidated into Dispose(bool) as the single idempotent cleanup point (releasing GCHandle, CancellationTokenRegistration, and JNI peer), replacing the old AbandonPin() method and fixing a pre-existing GCHandle leak on the sync-completion path.
  • The ContinueWith tail in Invoke<T> is replaced with a small async Task<T> AwaitAndUnbox(...) helper so that a cancelled TCS correctly surfaces as a Canceled (not Faulted) task through the async state machine.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/ComposeNet.Compose/SuspendContinuation.cs Adds CancellationTokenRegistration field, _disposed guard with Interlocked.Exchange, cancellation callback in ctor, and consolidated Dispose(bool) replacing AbandonPin()
src/ComposeNet.Compose/SuspendBridge.cs Adds CancellationToken parameter to both Invoke overloads, pre/post-registration checks, cont.Dispose() on sync paths (fixing leak), and replaces ContinueWith with AwaitAndUnbox async helper
src/ComposeNet.Compose/ScrollState.cs Threads CancellationToken through ScrollToAsync and AnimateScrollToAsync with accurate param docs
src/ComposeNet.Compose/PublicAPI.Unshipped.txt Updates both ScrollState async method signatures to include the new parameter
.github/copilot-instructions.md Documents cancellation semantics and updates *Async facade templates to always surface and forward the token

Comment thread src/ComposeNet.Compose/SuspendBridge.cs Resolved
Copilot review feedback on #137.

Co-authored-by: Copilot <[email protected]>
@jonathanpeppers
jonathanpeppers merged commit 951357b into main Jun 7, 2026
1 check passed
@jonathanpeppers
jonathanpeppers deleted the jonathanpeppers/suspend-cancellation-token branch June 7, 2026 20:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants