concurrency

Convention based Concurrency Management in Entity Framework Core

Who does not love convention over configuration? Whenever it makes sense I try to use it in my role as a system architect. It helps my programmers write more robust code out of the box.

Writing concurrency safe code is a corner stone in writing robust code today,  without it data quality can not be guaranteed. And when things go wrong you want to know who and when entities were updated so you can investigate what have gone wrong.

So what I did at my latest assignment was to force this onto the entities by convention using two markup interfaces ICreated and IUpdated(more…)

A proper thread safe memory cache

The Core 2.2 IMemoryCache is in theory thread safe. But if you call GetOrCreateAsync from multiple threads the factory Func will be called multiple times. Which could be a bad thing. A very simple fix to this is using a semaphore.

Declare it and only let one concurrent request be granted.

private readonly SemaphoreSlim _cacheLock = new SemaphoreSlim(1);

Let one request the cache and when done release the semaphore.

await _cacheLock.WaitAsync();
var data = await _cache.GetOrCreateAsync(key, entry => ...);
_cacheLock.Release();