Skip to content

[API Proposal]: Add async overload of ChangeToken.OnChange #69099

Closed

Description

@davidfowl

Background and motivation

Today it's not possible to use ChangeToken.OnChange to execute asynchronous logic before re-subscribing for new updates. The current API has an Action<T> based callback only. We need an async overload to run async logic so people don't end up using async void or blocking when using this helper.

API Proposal

 namespace Microsoft.Extensions.Primitives;

 public static class ChangeToken
 {
    // existing 
    // public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer);
    // public static IDisposable OnChange<TState>(
    //     Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state);

    public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Func<Task> changeTokenConsumer);
    public static IDisposable OnChange<TState>(
        Func<IChangeToken?> changeTokenProducer, Func<TState, Task> changeTokenConsumer, TState state);
 }

API Usage

using Microsoft.Extensions.Primitives;

var config = new ConfigurationBuilder().AddJsonFile("config.json", optional: false, reloadOnChange: true)
            .Build();

_ = ChangeToken.OnChange(config.GetReloadToken, async () =>
{
    await Task.Delay(1000);
    Console.WriteLine("Change happened");
});

Alternatives (added by @svick)

  • Add a CancellationToken parameter that's canceled when a following change is detected. This would probably be confusing, since not every caller would want to honor it and can be implemented by users if needed.
  • Change the name to OnAsyncChange (or similar). For those that use async lambda with OnChange today, this would be less breaking, but they wouldn't automatically get the benefit of the new version.

Risk (added by @svick)

This change means that existing code that uses an async lambda when calling OnChange will change meaning: previously, it compiled to an async void method; with this change, it will be an async Task method, where the callback is re-registered only once the returned Task completes. This could break some users, though the new behavior should be more correct.

Activity

  1. added
    api-suggestion
    on May 10, 2022
  2. ghost added
    untriaged
    on May 10, 2022
  3. removed
    untriaged
    on May 10, 2022
  4. added this to the Future milestone on May 10, 2022
  5. maryamariyan commented on May 10, 2022

    @maryamariyan
    Contributor

    Marked for future. @davidfowl is this a critical feature for 7.0?

  6. davidfowl commented on May 11, 2022

    @davidfowl
    MemberAuthor

    Critical, no but I can take it to API review and do the implementation if needed for .NET 7. It's currently a pit of failure (I filed this because I saw someone use it in a way that would fail).

  7. lonix1 commented on Jul 7, 2022

    @lonix1

    This would be highly appreciated!

    Another use case. There's double detection of changes to appsettings.json. There are still open issues for that. Those issues and the docs recommend debouncing the detections. But using the change token approach needs an async overload. (I documented the problem here).

  8. dazinator commented on Nov 9, 2022

    @dazinator

    I worked around this a while ago: https://github.com/dazinator/Changify/blob/develop/src/Changify/Extensions/ChangeTokenExtensions.cs

    Basically, in order to use ChangeToken.OnChange you need:

    • Func<IChangeToken> produces the token.
    • `Action`` is called when the token changes.

    So I wrote the above extension method for Func<IChangeToken> so you can do this:

    Func<IChangeToken> changeTokenProducer = GetOrInjectThis();
    
    await changeTokenProducer.WaitOneAsync();
    
    // token has been signalled do your async work here.
    await MyStuff();
    
    // One draw back of this approach is that it's one execution at a time, i.e so to listen for the next signal you have to make this call again or refactor this into a loop so can be used similar to ChangeToken.OnChange style.
    
     await changeTokenProducer.WaitOneAsync();
  9. davidfowl commented on Nov 9, 2022

    @davidfowl
    MemberAuthor

    One other idea is an IAsyncEnumerable approach?

  10. dazinator commented on Apr 28, 2023

    @dazinator

    Here is the implementation I landed on: https://github.com/dazinator/Changify/blob/develop/src/Changify/Extensions/ChangeTokenExtensions.cs#L78

    The reason the solution looks like this, to me, is basically because I was already familiar with this WaitOneAsync api - and did not want the cognitive load of trying to make an async equivalent to this:

    private sealed class ChangeTokenRegistration<TState> : IDisposable
    or solving from first principles ;-)

    and a test: https://github.com/dazinator/Changify/blob/develop/src/Changify.Tests/ChangeTokenExtensionsTests.cs#L76

    Saying that, even though it seems to be functional, I don't like the fact it's creating two TCS's per async callback.

    • The reason there is a single long running background task is it made it easy to process each token in a sequence for the duration of the subscription.
    • The reason this long runnign outer task doesn't directly await each async callback when a token is signalled, but instead schedules it as an independent task, is that this allows uncaught exceptions (e.g from the async callbacks) to be surfaced as they would do in the synchronous scenario, as shown in the test, whilst keeping the overall subscription alive- i.e the outer task will just continue to schedule the next task for the next token when the isolated task completes. So it was really me trying too keep the exception behaviour the same that lead me down the path of needed another TCS here.

    All in all I think this will serve my purposes for now, until either:

    • I want to revist from first principles again (i.e without skewing myself to use WaitOneAsync)
    • The dotnet team releases something better!
    • I (or someone else) creates a different consumer api over the top of change tokens - maybe IAsyncEnumerable based, I could imagine enumerating through an IAsyncEnumerable in a long running background thread for example to process something asynchronously in each iteration in response to a change token firing - basically this would not look like the current ChangeToken.OnChange api.

    @davidfowl
    one thing which I was curious about is that.. the consumer could unregister from callbacks at any point on another thread for example. Meanwhile an async callback could about to be invoked, or could even be running. It felt to me like it might be nice to supply a CancellationToken into the callback which could be signalled if the consumer unsubscribes. However this isn't part of the api at present. Use case would be, the async task does something resource intensive, and if the consumer is no longer interested in being notified, perhaps thats another way of them indicating that even if a callback is currently running, they wish it to be terminated? I am not sure about this perhaps this a seperate thing that they can workaround via their own mechanisms - passing state and such.

  11. 17 remaining items

  12. added
    api-suggestion
    api-ready-for-review
    and removed
    api-suggestion
    on Mar 5, 2026
  13. bartonjs commented on Apr 14, 2026

    @bartonjs
    Member

    Video

    • We discussed CancellationToken, and while it's not visible in the API, it's possible (without capture) via the TState overload.
    • We discussed whether the async-void parallel vs serial behavior was good to do (overload) or bad (new method group) and feel that an overload is better.
     namespace Microsoft.Extensions.Primitives;
    
     public static class ChangeToken
     {
        public static IDisposable OnChange(
            Func<IChangeToken?> changeTokenProducer, Func<Task> changeTokenConsumer);
        public static IDisposable OnChange<TState>(
            Func<IChangeToken?> changeTokenProducer, Func<TState, Task> changeTokenConsumer, TState state);
     }
  14. added
    api-approved
    breaking-change
    needs-breaking-change-doc-created
    and removed
    api-ready-for-review
    on Apr 14, 2026
  15. dotnet-policy-service commented on Apr 14, 2026

    @dotnet-policy-service
    Contributor

    Added needs-breaking-change-doc-created label because this issue has the breaking-change label.

    1. Create and link to this issue a matching issue in the dotnet/docs repo using the breaking change documentation template, then remove this needs-breaking-change-doc-created label.

    Tagging @dotnet/compat for awareness of the breaking change.

  16. added
    in-pr
    on Jun 24, 2026
  17. added a commit that references this issue on Jul 3, 2026
    6814be7
  18. added a commit that references this issue on Jul 15, 2026
    ac96c86
  19. locked and limited conversation to collaborators on Aug 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-Extensions-Primitivesbreaking-changein-prneeds-breaking-change-doc-created

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions