The given code attempts to run a fire-and-forget Task
while acquiring a lock to avoid race conditions on a cached element.
while debugging the whole application I noticed bizarre behavior - getting to the same break point with the same key. That said, I'm not sure if the assumption that ConcurrentDictionary
guarantees that only one writer will be applied to the element as well as locking inside the Task.Run
block will assure me that this and only this Task will have access to the element itself.
Task.Run(() =>
{
lock (GetLockContext(key, region))
{
try
{
object newValue = cacheInterceptor.Intercept<T>(ctx);
Put(refreshContext.Key, newValue, refreshContext.Region, refreshAction);
}
catch (Exception ex)
{
refreshContext.UpdteRefreshNeeded(true);
LogError("HANDLE_REFRESH", null, null, ex);
}
});
}
private object GetLockContext(string key, string region)
{
string ctx = key + region;
object lckCtx = CTX_REPO.GetOrAdd(ctx, (dontcare) => new object());
return lckCtx;
}
private static readonly ConcurrentDictionary<string, object> CTX_REPO