How can I limit access to a particular class to one caller at a time in a web service?

Posted by MusiGenesis on Stack Overflow See other posts from Stack Overflow or by MusiGenesis
Published on 2010-04-14T01:11:03Z Indexed on 2010/04/14 1:13 UTC
Read the original article Hit count: 392

Filed under:
|
|
|
|

I have a web service method in which I create a particular type of object, use it for a few seconds, and then dispose it. Because of problems arising from multiple threads creating and using instances of this class at the same time, I need to restrict the method so that only one caller at a time ever has one of these objects.

To do this, I am creating a private static object:

private static object _lock = new object();

... and then inside the web service method I do this around the critical code:

lock (_lock)
{
    using (DangerousObject do = new DangerousObject())
    {
        do.MakeABigMess();
        do.CleanItUp();
    }
}

I'm not sure this is working, though. Do I have this right? Will this code ensure that only one instance of DangerousObject is instantiated and in use at a time?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET