Keyed Lock in .Net

后端 未结 3 2011
长发绾君心
长发绾君心 2021-01-21 20:02

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

3条回答
  •  时光说笑
    2021-01-21 20:39

    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.

提交回复
热议问题