Locking by string. Is this safe/sane?

前端 未结 9 1633
-上瘾入骨i
-上瘾入骨i 2020-12-14 01:33

I need to lock a section of code by string. Of course the following code is hideously unsafe:

lock(\"http://someurl\")
{
    //bla
}

So I\'

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 01:56

    Here is a very simple, elegant and correct solution for .NET 4 using ConcurrentDictionary adapted from this question.

    public static class StringLocker
    {
        private static readonly ConcurrentDictionary _locks = new ConcurrentDictionary();
    
        public static void DoAction(string s, Action action)
        {
            lock(_locks.GetOrAdd(s, new object()))
            {
                action();
            }
        }
    }
    

    You can use this like so:

    StringLocker.DoAction("http://someurl", () =>
    {
        ...
    });
    

提交回复
热议问题