ASP.NET Core | Change Token
A change token in ASP.NET Core is a general-purpose, low-level building block used to track state changes. Let me break it down for you:
IChangeToken Interface:
- The
IChangeTokeninterface propagates notifications that a change has occurred. - It resides in the
Microsoft.Extensions.Primitivesnamespace and is implicitly provided to ASP.NET Core apps via theMicrosoft.Extensions.PrimitivesNuGet package. - Key properties:
ActiveChangeCallbacks: Indicates whether the token proactively raises callbacks. If set tofalse, a callback is never called, and the app must pollHasChangedfor changes.HasChanged: Receives a value that indicates if a change has occurred.
- Additionally, it includes the
RegisterChangeCallback(Action<Object>, Object)method, which registers a callback invoked when the token changes1.
- The
ChangeToken Class:
- The
ChangeTokenclass is static and used to propagate notifications that a change has occurred. - It also resides in the
Microsoft.Extensions.Primitivesnamespace and is implicitly provided to ASP.NET Core apps. - The
ChangeToken.OnChange(Func<IChangeToken>, Action)method registers an action to call whenever the token changes:Func<IChangeToken>produces the token.- The
Actionis called when the token changes. - The overload
ChangeToken.OnChange<TState>(Func<IChangeToken>, Action<TState>, TState)takes an additionalTStateparameter passed into the token consumer action. - The
OnChangemethod returns anIDisposable, and callingDisposestops the token from listening for further changes and releases its resources.
- The
Example Uses of Change Tokens:
- Change tokens are used in several areas of ASP.NET Core:
- File Monitoring: For monitoring changes to files, the
IFileProvider’sWatchmethod creates anIChangeTokenfor specified files or folders. - Cache Evictions: IChangeTokens can be added to cache entries to trigger cache evictions when changes occur.
- TOptions Changes: The default
OptionsMonitor<TOptions>implementation ofIOptionsMonitor<TOptions>accepts one or moreIOptionsChangeTokenSource<TOptions>instances. Each instance returns anIChangeTokenfor tracking options changes1.
- File Monitoring: For monitoring changes to files, the
- Change tokens are used in several areas of ASP.NET Core:
In summary, change tokens provide a flexible mechanism for tracking changes in various scenarios within ASP.NET Core applications. They allow efficient handling of state changes without unnecessary polling or resource consumption
Comments
Post a Comment