Skip to content

Commit

Permalink
Add example for caching.
Browse files Browse the repository at this point in the history
This not only helps try out library but also encourages future contribution to issue dotnet#67770.
  • Loading branch information
maryamariyan committed Nov 18, 2022
1 parent e744280 commit 7075102
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/libraries/Microsoft.Extensions.Caching.Memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,40 @@ In-memory caching provides a general purpose memory implementation of the core c

Documentation can be found at https://learn.microsoft.com/en-us/dotnet/core/extensions/caching.

## Example

The following example shows how to instantiate a single memory cache using `AddMemoryCache` API and via DI get it injected to enable them calling `GetCurrentStatistics`

```c#
// when using `services.AddMemoryCache(options => options.TrackStatistics = true);` to instantiate
[EventSource(Name = "Microsoft-Extensions-Caching-Memory")]
internal sealed class CachingEventSource : EventSource
{
public CachingEventSource(IMemoryCache memoryCache) { _memoryCache = memoryCache; }
protected override void OnEventCommand(EventCommandEventArgs command)
{
if (command.Command == EventCommand.Enable)
{
if (_cacheHitsCounter == null)
{
_cacheHitsCounter = new PollingCounter("cache-hits", this, () =>
_memoryCache.GetCurrentStatistics().CacheHits)
{
DisplayName = "Cache hits",
};
}
}
}
}
```

The stats can be viewed using the above event counter like below with `dotnet-counters` tool:

<img width="400" alt="image" src="https://user-images.githubusercontent.com/5897654/156053460-46db5070-04b0-478c-9013-ab0298a7b1ec.png">

To learn more about using memory cache and getting statistics check out issue dotnet/runtime#67770.

## Contribution Bar
- [x] [We consider new features, new APIs, bug fixes, and performance changes](../../libraries/README.md#primary-bar)

Expand Down

0 comments on commit 7075102

Please sign in to comment.