I have a Azure Service Bus queue where I\'m receiving a range from 1 to 10 messages with the same \"key\". One of these messages needs to be processed with a long running operat
You correctly recognized that you need to ensure that only one semaphore is being created per key. The standard idiom for that is:
var dict = new ConcurrentDictionary>();
...
var sem = dict.GetOrAdd( , _ => new new Lazy(() => SemaphoreSlim(1, 1))).Value;
Multiple lazies might be created but only one of them will ever be revealed and materialized.
Besides that it is a questionable practice to rely on in-memory state. What if your queue processing app recycles and all semaphores are lost? You better use a persistent store to track this locking info.