ConcurrentDictionary
We can improve the implementation of CustomProvider
using ConcurrentDictionary<TKey, TValue>
to handle the synchronization:
public class CustomProvider { private readonly ConcurrentDictionary<string, OperationResult> _cache = new ConcurrentDictionary<string, OperationResult>(); public OperationResult RunOperationOrGetFromCache( string operationId) { return _cache.GetOrAdd(operationId, id => RunLongRunningOperation(id)); } private OperationResult RunLongRunningOperation( string operationId) { // Running real long-running operation // ... Console.WriteLine("Running long-running operation"); return OperationResult.Create(operationId); } }
The code became much simpler. We just used the GetOrAdd
method and it does exactly what we ...
Get Mastering C# Concurrency now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.