Repository navigation
Add CancellationToken support to SuspendBridge - #137
Merged
Merged
Conversation
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]>
There was a problem hiding this comment.
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 bothScrollStateasync facades now acceptCancellationToken cancellationToken = default, with a pre-check, post-registration re-check, and allocation-freeRegistercallback that callsTrySetCanceledon the backing TCS.SuspendContinuationlifecycle is consolidated intoDispose(bool)as the single idempotent cleanup point (releasingGCHandle,CancellationTokenRegistration, and JNI peer), replacing the oldAbandonPin()method and fixing a pre-existing GCHandle leak on the sync-completion path.- The
ContinueWithtail inInvoke<T>is replaced with a smallasync 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 |
Copilot review feedback on #137. Co-authored-by: Copilot <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 twoScrollStateasync facades (ScrollToAsync,AnimateScrollToAsync) now take a trailingCancellationToken cancellationToken = default. When the token fires, the returned task transitions to Canceled (OperationCanceledExceptionat the awaiter) via the allocation-freeCancellationToken.Register((state, token) => ...)overload callingTcs.TrySetCanceled(token).Three secondary cleanups fell out of this:
IDisposable.Java.Lang.Objectalready implementsIDisposable, and in every code path Kotlin is done with the continuation by the time we clean up (sync-throw, sync-completion, post-ResumeWithsingle-resume contract). The previousAbandonPin()method is gone;Dispose(bool)is now the single, idempotent cleanup point that releases theGCHandleself-pin, disposes theCancellationTokenRegistration, and lets the base call release the JNI peer. Guarded byInterlocked.Exchange(ref _disposed, true).ContinueWithtail with a smallasync Task<T> AwaitAndUnbox(...)helper. A cancelled TCS now surfaces as a Canceled (not Faulted) task because the async state machine routes the uncaughtOperationCanceledExceptionstraight intoAsyncTaskMethodBuilder.SetCanceled.GCHandleself-pin. The newcont.Dispose()call on that path closes it.Cancellation semantics (intentional, documented)
This is the "simple" /
#1456-shaped cancel: the awaiter seesOperationCanceledExceptionimmediately, but the Kotlin suspend body continues to its natural completion. We don't yet wire aJobintoSuspendContinuation.Context, so there is no Kotlin-side cancel. When Kotlin eventually resumes,CompleteWithLocalHandlesees 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 forJobKt.Job()+CoroutineContext.plus()+Job.cancel()plusResult.Failure(CancellationException)routing. Left as a follow-up; called out in theSuspendBridgeXML doc and in the suspend section of.github/copilot-instructions.md(which also has the updated facade template).Verification
ComposeNet.ComposeandComposeNet.Samplebuild clean (0 warnings, 0 errors).ComposeNet.SourceGenerators.Tests: 105/105 passing.Registerre-check ofIsCancellationRequestedcovers 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.