Вопрос

There's a simple web service method like this:

public string AppendOne(string ID)
{
    Thread.Sleep(5000);
    return ID+"One";    
}

I want to prevent this method to process multiple calls with same parameter (ID) at the same time.

For example Client1 called this method with parameter "ABC". Until it finishes, if Client2 calls the same method with same parameter "ABC", it should wait for Client1 to finish it's job, then start. if Client3 calls the method at the same time with parameter "DEF", it should process without waiting.

How can i achieve this with object locking?

I tried this, assuming String object is pointing to the same address in memory but no success.

public string AppendOne(string ID)
{
    lock (ID)
    {
         Thread.Sleep(5000);
         return ID+"One";   
    }
}
Это было полезно?

Решение

You cannot assume that a string with the same value points to the same memory location. So the mmemory can contain two or more instances with 'ABC'. In that case your lock will not work.

Luckily .NET has a trick: string.Intern(). See: http://msdn.microsoft.com/en-us/library/system.string.intern(v=vs.110).aspx

This function will store or locate your string in some kind of internal dictionary. If the value is new, he will add it into the dictionary. If it already exists, the original value is returned, resulting in one address to strings with the same value.

public string AppendOne(string ID)
{
    lock (string.Intern(ID))
    {
         Thread.Sleep(5000);
         return ID+"One";   
    }
}

Warning: If ID is null, you will get a exception. You might wanna test on that first.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top