I am creating a web service that uses a component I've licensed that is restricted to two concurrent instances at any one time. Creating a new instance of the component takes a long time (seconds) so I want to maintain a pool of objects for re-use. Here's my first (working) attempt, but it seems fairly inelegant, and also likely that I've made some mistakes (although it hasn't failed in my own tests):
public class MyWebService : System.Web.Services.WebService
{
static RestrictedClass rc1, rc2;
[WebMethod]
public byte[] MyMethod(byte[] Stream1, byte[] Stream2)
{
RestrictedClass rc = null;
Mutex m1 = null, m2 = null;
if (rc1 == null)
{
m1 = new Mutex(true, "rc1");
m1.WaitOne();
rc1 = new RestrictedClass();
rc = rc1;
}
else if (rc2 == null)
{
m2 = new Mutex(true, "rc2");
m2.WaitOne();
rc2 = new RestrictedClass();
rc = rc2;
}
else
{
bool m1Granted, m2Granted;
m1 = new Mutex(true, "rc1", out m1Granted);
m2 = new Mutex(true, "rc2", out m2Granted);
int idx;
if (m1Granted)
{
idx = 0;
}
else if (m2Granted)
{
idx = 1;
}
else
{
idx = Mutex.WaitAny(new Mutex[] { m1, m2 });
}
if (idx == 0)
{
rc = rc1;
m2.Close();
}
else if (idx == 1)
{
rc = rc2;
m1.Close();
}
}
Result = rc.DoStuff();
if (m1 != null && rc == rc1)
m1.ReleaseMutex();
if (m2 != null && rc == rc2)
m2.ReleaseMutex();
return Result.ToArray();
}
}
Please pick it apart and suggest any improvements you like.
MyMethod
could beGetComponentFromPool
or anything else that is at least meaningful.MyWebService
could beComponentPoolService
. And all these abbreviations. I find your sample is almost incomprehensible. If your real code looks like this then I would't want to maintain it. \$\endgroup\$