I need to lock a section of code by string. Of course the following code is hideously unsafe:
lock(\"http://someurl\")
{
//bla
}
So I\'
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", () =>
{
...
});