Skip to content

Commit 6814be7

Browse files
svickCopilottarekgh
authored
Added async overload of ChangeToken.OnChange (#129624)
Fixes #69099. Adds async (`Func<Task>`) overloads of `ChangeToken.OnChange`, so callers can run asynchronous logic when a change token fires without resorting to `async void` or blocking: ```csharp public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Func<Task> changeTokenConsumer); public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Func<TState, Task> changeTokenConsumer, TState state); ``` These match the shape approved in #69099. ## Behavior The existing `ChangeTokenRegistration<TState>` is refactored into an abstract base class holding the registration/disposal state machine, with `SyncChangeTokenRegistration` and `AsyncChangeTokenRegistration` subclasses. The synchronous overloads behave exactly as before. For the async overloads: - The consumer is invoked synchronously, so **synchronous** exceptions from it are propagated to the code that triggers the change token, just like the synchronous overloads. - The change token is only re-registered once the returned `Task` completes. Changes that occur while the consumer's task is still in flight are coalesced into a single subsequent invocation. - **Asynchronous** faults from the consumer's task cannot be propagated without blocking, so they are left unobserved (observable only through `TaskScheduler.UnobservedTaskException`). This is documented in the API remarks. - When the consumer completes synchronously, re-registration happens without allocating an async state machine. ## Breaking change This is a source (not binary) breaking change, as called out in the proposal's Risk section: existing code that passes an `async` lambda to `OnChange` previously bound to the `Action` overload (compiling to `async void` / fire-and-forget). With these overloads present, such call sites now bind to the `Func<Task>` overload and re-registration is deferred until the returned task completes. The new behavior is generally more correct. A throwing statement lambda can also become ambiguous between `Action` and `Func<Task>` (CS0121); the two pre-existing tests affected were updated with explicit `(Action)` casts. ## Tests - Null-argument validation for all four overloads. - Change firing (with and without state) for the async overloads. - Disposal stops further consumer invocations. - Re-registration is deferred until the consumer's task completes (in-flight changes coalesce). - Synchronous consumer exceptions propagate to the trigger; asynchronous faults do not; the subscription survives both. - Producer exceptions during initial registration propagate to the caller; producer exceptions when the token fires propagate to the trigger (all four overloads). - Disposal during a running consumer (both from within the consumer and from another thread) suppresses re-registration. The cross-thread case requires real multithreading and is gated with `[ConditionalTheory(... IsMultithreadingSupported)]`. > [!NOTE] > This PR description was generated by GitHub Copilot. --------- Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Tarek Mahmoud Sayed <10833894+tarekgh@users.noreply.github.com>
1 parent 412dcde commit 6814be7

5 files changed

Lines changed: 739 additions & 51 deletions

File tree

‎src/libraries/Microsoft.Extensions.Primitives/ref/Microsoft.Extensions.Primitives.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ public CancellationChangeToken(System.Threading.CancellationToken cancellationTo
1616
public static partial class ChangeToken
1717
{
1818
public static System.IDisposable OnChange(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action changeTokenConsumer) { throw null; }
19+
public static System.IDisposable OnChange(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Func<System.Threading.Tasks.Task> changeTokenConsumer) { throw null; }
1920
public static System.IDisposable OnChange<TState>(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Action<TState> changeTokenConsumer, TState state) { throw null; }
21+
public static System.IDisposable OnChange<TState>(System.Func<Microsoft.Extensions.Primitives.IChangeToken?> changeTokenProducer, System.Func<TState, System.Threading.Tasks.Task> changeTokenConsumer, TState state) { throw null; }
2022
}
2123
public partial class CompositeChangeToken : Microsoft.Extensions.Primitives.IChangeToken
2224
{

‎src/libraries/Microsoft.Extensions.Primitives/src/ChangeToken.cs‎

Lines changed: 186 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Threading;
6+
using System.Threading.Tasks;
67

78
namespace Microsoft.Extensions.Primitives
89
{
@@ -15,8 +16,12 @@ public static class ChangeToken
1516
/// Registers the <paramref name="changeTokenConsumer"/> action to be called whenever the token produced changes.
1617
/// </summary>
1718
/// <param name="changeTokenProducer">Produces the change token.</param>
18-
/// <param name="changeTokenConsumer">Action called when the token changes.</param>
19-
/// <returns></returns>
19+
/// <param name="changeTokenConsumer">Action called when the token changes. The token is re-registered once the action returns.</param>
20+
/// <returns>An <see cref="IDisposable"/> that, when disposed, unregisters the consumer.</returns>
21+
/// <remarks>
22+
/// Exceptions from <paramref name="changeTokenProducer"/> are propagated to the caller of this method or to the code that triggers the change token.
23+
/// Exceptions from <paramref name="changeTokenConsumer"/> are propagated to the code that triggers the change token.
24+
/// </remarks>
2025
public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer)
2126
{
2227
if (changeTokenProducer is null)
@@ -28,16 +33,20 @@ public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Acti
2833
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
2934
}
3035

31-
return new ChangeTokenRegistration<Action>(changeTokenProducer, callback => callback(), changeTokenConsumer);
36+
return new SyncChangeTokenRegistration<Action>(changeTokenProducer, static callback => callback(), changeTokenConsumer);
3237
}
3338

3439
/// <summary>
3540
/// Registers the <paramref name="changeTokenConsumer"/> action to be called whenever the token produced changes.
3641
/// </summary>
3742
/// <param name="changeTokenProducer">Produces the change token.</param>
38-
/// <param name="changeTokenConsumer">Action called when the token changes.</param>
43+
/// <param name="changeTokenConsumer">Action called when the token changes. The token is re-registered once the action returns.</param>
3944
/// <param name="state">state for the consumer.</param>
40-
/// <returns></returns>
45+
/// <returns>An <see cref="IDisposable"/> that, when disposed, unregisters the consumer.</returns>
46+
/// <remarks>
47+
/// Exceptions from <paramref name="changeTokenProducer"/> are propagated to the caller of this method or to the code that triggers the change token.
48+
/// Exceptions from <paramref name="changeTokenConsumer"/> are propagated to the code that triggers the change token.
49+
/// </remarks>
4150
public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
4251
{
4352
if (changeTokenProducer is null)
@@ -49,65 +58,97 @@ public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProduc
4958
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
5059
}
5160

52-
return new ChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state);
61+
return new SyncChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state);
5362
}
5463

55-
private sealed class ChangeTokenRegistration<TState> : IDisposable
64+
/// <summary>
65+
/// Registers the <paramref name="changeTokenConsumer"/> function to be called whenever the token produced changes.
66+
/// </summary>
67+
/// <param name="changeTokenProducer">Produces the change token.</param>
68+
/// <param name="changeTokenConsumer">Function called when the token changes. The token is only re-registered once the returned <see cref="Task"/> completes.</param>
69+
/// <returns>An <see cref="IDisposable"/> that, when disposed, unregisters the consumer.</returns>
70+
/// <remarks>
71+
/// Exceptions from <paramref name="changeTokenProducer"/> are propagated to the caller of this method or to the code that triggers the change token.
72+
/// Synchronous exceptions from <paramref name="changeTokenConsumer"/> are propagated to the code that triggers the change token.
73+
/// Asynchronous exceptions from <paramref name="changeTokenConsumer"/> are left unobserved.
74+
/// </remarks>
75+
public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Func<Task> changeTokenConsumer)
76+
{
77+
if (changeTokenProducer is null)
78+
{
79+
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
80+
}
81+
if (changeTokenConsumer is null)
82+
{
83+
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
84+
}
85+
86+
return new AsyncChangeTokenRegistration<Func<Task>>(changeTokenProducer, static callback => callback(), changeTokenConsumer);
87+
}
88+
89+
/// <summary>
90+
/// Registers the <paramref name="changeTokenConsumer"/> function to be called whenever the token produced changes.
91+
/// </summary>
92+
/// <param name="changeTokenProducer">Produces the change token.</param>
93+
/// <param name="changeTokenConsumer">Function called when the token changes. The token is only re-registered once the returned <see cref="Task"/> completes.</param>
94+
/// <param name="state">state for the consumer.</param>
95+
/// <returns>An <see cref="IDisposable"/> that, when disposed, unregisters the consumer.</returns>
96+
/// <remarks>
97+
/// Exceptions from <paramref name="changeTokenProducer"/> are propagated to the caller of this method or to the code that triggers the change token.
98+
/// Synchronous exceptions from <paramref name="changeTokenConsumer"/> are propagated to the code that triggers the change token.
99+
/// Asynchronous exceptions from <paramref name="changeTokenConsumer"/> are left unobserved.
100+
/// </remarks>
101+
public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Func<TState, Task> changeTokenConsumer, TState state)
102+
{
103+
if (changeTokenProducer is null)
104+
{
105+
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
106+
}
107+
if (changeTokenConsumer is null)
108+
{
109+
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
110+
}
111+
112+
return new AsyncChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state);
113+
}
114+
115+
private abstract class ChangeTokenRegistration<TState>(Func<IChangeToken?> changeTokenProducer, TState state) : IDisposable
56116
{
57-
private readonly Func<IChangeToken?> _changeTokenProducer;
58-
private readonly Action<TState> _changeTokenConsumer;
59-
private readonly TState _state;
60117
private IDisposable? _disposable;
61118

62119
private static readonly NoopDisposable _disposedSentinel = new NoopDisposable();
63120

64-
public ChangeTokenRegistration(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
65-
{
66-
_changeTokenProducer = changeTokenProducer;
67-
_changeTokenConsumer = changeTokenConsumer;
68-
_state = state;
121+
protected TState State { get; } = state;
69122

70-
IChangeToken? token = changeTokenProducer();
123+
protected Func<IChangeToken?> ChangeTokenProducer { get; } = changeTokenProducer;
71124

72-
RegisterChangeTokenCallback(token);
73-
}
125+
protected abstract void OnChangeTokenFired();
74126

75-
private void OnChangeTokenFired()
127+
protected void RegisterChangeTokenCallback(IChangeToken? token)
76128
{
77-
// The order here is important. We need to take the token and then apply our changes BEFORE
78-
// registering. This prevents us from possible having two change updates to process concurrently.
79-
//
80-
// If the token changes after we take the token, then we'll process the update immediately upon
81-
// registering the callback.
82-
IChangeToken? token = _changeTokenProducer();
83-
84-
try
85-
{
86-
_changeTokenConsumer(_state);
87-
}
88-
finally
129+
if (token is null)
89130
{
90-
// We always want to ensure the callback is registered
91-
RegisterChangeTokenCallback(token);
131+
return;
92132
}
93-
}
94133

95-
private void RegisterChangeTokenCallback(IChangeToken? token)
96-
{
97-
if (token is null)
134+
// If the registration has already been disposed, don't register again. This guards re-registration
135+
// after disposal: registering on a token that has already changed invokes the callback synchronously, which
136+
// would re-run the consumer after disposal.
137+
if (Volatile.Read(ref _disposable) == _disposedSentinel)
98138
{
99139
return;
100140
}
101-
IDisposable registraton = token.RegisterChangeCallback(s => ((ChangeTokenRegistration<TState>?)s)!.OnChangeTokenFired(), this);
141+
142+
IDisposable? registration = token.RegisterChangeCallback(static s => ((ChangeTokenRegistration<TState>?)s)!.OnChangeTokenFired(), this);
102143
if (token.HasChanged && token.ActiveChangeCallbacks)
103144
{
104-
registraton?.Dispose();
145+
registration?.Dispose();
105146
return;
106147
}
107-
SetDisposable(registraton);
148+
SetDisposable(registration);
108149
}
109150

110-
private void SetDisposable(IDisposable disposable)
151+
private void SetDisposable(IDisposable? disposable)
111152
{
112153
// We don't want to transition from _disposedSentinel => anything since it's terminal
113154
// but we want to allow going from previously assigned disposable, to another
@@ -117,7 +158,7 @@ private void SetDisposable(IDisposable disposable)
117158
// If Dispose was called, then immediately dispose the disposable
118159
if (current == _disposedSentinel)
119160
{
120-
disposable.Dispose();
161+
disposable?.Dispose();
121162
return;
122163
}
123164

@@ -127,7 +168,7 @@ private void SetDisposable(IDisposable disposable)
127168
if (previous == _disposedSentinel)
128169
{
129170
// The subscription was disposed so we dispose immediately and return
130-
disposable.Dispose();
171+
disposable?.Dispose();
131172
}
132173
else if (previous == current)
133174
{
@@ -136,7 +177,7 @@ private void SetDisposable(IDisposable disposable)
136177
else
137178
{
138179
// Sets can never overlap with other SetDisposable calls so we should never get into this situation
139-
throw new InvalidOperationException("Somebody else set the _disposable field");
180+
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_ConcurrentDisposableSet);
140181
}
141182
}
142183

@@ -154,5 +195,106 @@ public void Dispose()
154195
}
155196
}
156197
}
198+
199+
private sealed class SyncChangeTokenRegistration<TState> : ChangeTokenRegistration<TState>
200+
{
201+
private readonly Action<TState> _changeTokenConsumer;
202+
203+
public SyncChangeTokenRegistration(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
204+
: base(changeTokenProducer, state)
205+
{
206+
_changeTokenConsumer = changeTokenConsumer;
207+
208+
RegisterChangeTokenCallback(changeTokenProducer());
209+
}
210+
211+
protected override void OnChangeTokenFired()
212+
{
213+
// The order here is important. We need to take the token and then apply our changes BEFORE
214+
// registering. This prevents us from possible having two change updates to process concurrently.
215+
//
216+
// If the token changes after we take the token, then we'll process the update immediately upon
217+
// registering the callback.
218+
IChangeToken? token = ChangeTokenProducer();
219+
220+
try
221+
{
222+
_changeTokenConsumer(State);
223+
}
224+
finally
225+
{
226+
// We always want to ensure the callback is registered
227+
RegisterChangeTokenCallback(token);
228+
}
229+
}
230+
}
231+
232+
private sealed class AsyncChangeTokenRegistration<TState> : ChangeTokenRegistration<TState>
233+
{
234+
private readonly Func<TState, Task> _changeTokenConsumer;
235+
236+
public AsyncChangeTokenRegistration(Func<IChangeToken?> changeTokenProducer, Func<TState, Task> changeTokenConsumer, TState state)
237+
: base(changeTokenProducer, state)
238+
{
239+
_changeTokenConsumer = changeTokenConsumer;
240+
241+
RegisterChangeTokenCallback(changeTokenProducer());
242+
}
243+
244+
protected override void OnChangeTokenFired()
245+
{
246+
// The order here is important. We need to take the token and then apply our changes BEFORE
247+
// registering. This prevents us from possible having two change updates to process concurrently.
248+
//
249+
// If the token changes after we take the token, then we'll process the update immediately upon
250+
// registering the callback once the consumer's task completes.
251+
IChangeToken? token = ChangeTokenProducer();
252+
253+
Task consumerTask;
254+
try
255+
{
256+
// The consumer is invoked synchronously here, so that synchronous exceptions from it are propagated
257+
// to the code that triggers the change token, just like the sync overload does.
258+
consumerTask = _changeTokenConsumer(State);
259+
}
260+
catch
261+
{
262+
// We always want to ensure the callback is registered, even when the consumer throws synchronously.
263+
RegisterChangeTokenCallback(token);
264+
throw;
265+
}
266+
267+
if (consumerTask is null)
268+
{
269+
RegisterChangeTokenCallback(token);
270+
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullConsumerTask);
271+
}
272+
273+
if (consumerTask.Status == TaskStatus.RanToCompletion)
274+
{
275+
// The common case where the consumer completes synchronously: re-register without allocations.
276+
RegisterChangeTokenCallback(token);
277+
}
278+
else
279+
{
280+
// Asynchronous exceptions can't be propagated without blocking, so they are left unobserved
281+
// (meaning they can be observed only through TaskScheduler.UnobservedTaskException).
282+
_ = AwaitConsumerAndRegisterCallback(consumerTask, token);
283+
}
284+
}
285+
286+
private async Task AwaitConsumerAndRegisterCallback(Task consumerTask, IChangeToken? token)
287+
{
288+
try
289+
{
290+
await consumerTask.ConfigureAwait(false);
291+
}
292+
finally
293+
{
294+
// We always want to ensure the callback is registered
295+
RegisterChangeTokenCallback(token);
296+
}
297+
}
298+
}
157299
}
158300
}

‎src/libraries/Microsoft.Extensions.Primitives/src/Resources/Strings.resx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,10 @@
132132
<data name="Capacity_NotUsedEntirely" xml:space="preserve">
133133
<value>Entire reserved capacity was not used. Capacity: '{0}', written '{1}'.</value>
134134
</data>
135+
<data name="InvalidOperation_ConcurrentDisposableSet" xml:space="preserve">
136+
<value>The change token callback registration was set concurrently, which is not supported.</value>
137+
</data>
138+
<data name="InvalidOperation_NullConsumerTask" xml:space="preserve">
139+
<value>The change token consumer returned a null task.</value>
140+
</data>
135141
</root>

‎src/libraries/Microsoft.Extensions.Primitives/src/ThrowHelper.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ private static string GetResourceText(ExceptionResource resource)
6868
case ExceptionResource.Capacity_CannotChangeAfterWriteStarted: return SR.Capacity_CannotChangeAfterWriteStarted;
6969
case ExceptionResource.Capacity_NotEnough: return SR.Capacity_NotEnough;
7070
case ExceptionResource.Capacity_NotUsedEntirely: return SR.Capacity_NotUsedEntirely;
71+
case ExceptionResource.InvalidOperation_ConcurrentDisposableSet: return SR.InvalidOperation_ConcurrentDisposableSet;
72+
case ExceptionResource.InvalidOperation_NullConsumerTask: return SR.InvalidOperation_NullConsumerTask;
7173
default:
7274
Debug.Fail($"Unexpected resource {resource}");
7375
return "";
@@ -108,6 +110,8 @@ internal enum ExceptionResource
108110
Argument_InvalidOffsetLengthStringSegment,
109111
Capacity_CannotChangeAfterWriteStarted,
110112
Capacity_NotEnough,
111-
Capacity_NotUsedEntirely
113+
Capacity_NotUsedEntirely,
114+
InvalidOperation_ConcurrentDisposableSet,
115+
InvalidOperation_NullConsumerTask
112116
}
113117
}

0 commit comments

Comments
 (0)