I have a .net core razor app that has a special use case where I need to have a global counter that will be incremented by every request, and yet it should remain thread-safe.
Also at web application load, this counter will be read from a database using entity framework.
I don't think that static variables are threadsafe for this scenario (since it can be read by a request then be modified after another request read its previous value).
So I was wondering if a locking mechanism is needed, or should a concurrent dictionary with a LazyLazy<T>
be used?
public static void PrintValueLazy(string valueToPrint)
{
var valueFound = _lazyDictionary.GetOrAdd("key",
x => new Lazy<string>(
() =>
{
Interlocked.Increment(ref _runCount);
Thread.Sleep(100);
return valueToPrint;
}));
Console.WriteLine(valueFound.Value);
}