Have you ever heard of or used the change tokens before? Basically, it helps us to track state changes (that’s it!).
.NET makes use of change tokens in a crucial part of the system, in configuration providers! Let’s say you want to reload configuration values in runtime and decided to use IOptionsMonitor or IOptionsSnapshot interface. Whenever you update your configuration source (appsettings.json file, keyvault, etc.) your classes will use the updated version of it. And as you may already guess this is the place where change tokens come into play.
Now, I am going to share some code snippets to show you how to use a change token to track changes in your model.
In this sample, we will have a guest list and want to keep track of that list. First, we’ll create the GuestListSource class.
GuestListSource.cs
As you see the class has some logic in it so it’s a rich domain model. I added some methods here so users of this class can use them to manipulate the data. In this way, it will be easier to track changes.
Now, let’s update the class to add a change-tracking feature. A Watch() method will be added. And later on, we will call that method in the Program.cs to track changes.
GuestListSource.cs
I used the CancellationTokenSource to create a new change token. Our goal is whenever the list got updated the Changed() method will be called and the cancellation token will be canceled.
In short, a canceled token means the data has changed.
The user of the Watch() method will get the created IChangeToken so it will be aware of when the token is canceled. Let’s show the Watcher part of it.
Program.cs
WatchHelper.cs
ChangeToken class has the OnChange method that accepts a producer and a consumer. Flow works like this;
- You get the change token from the producer (GuestListSource.Watch()) and wait until the token gets canceled which means the list has been updated.
- The token gets canceled and the OnChange method calls the Watch() method again and gets a new token and also runs the consumer part of the code, in our case Debug.WriteLine(“Guest list has been changed”).
Important Note
This is just one way of using change tokens, you will see different implementations in the wild. I’ve shared this example to give you some context around it.
And that’s all I have for this article. It’s really nice to have this kind of feature under the hood so you don’t need to import a new library or write the whole logic for your use case.
I tried to use a simple example to show how to use a ChangeToken in your model. I hope it helps and please feel free to make additions/suggestions.