M
Marty McDonald
public static object GetInstance(Type type, object[] args)
{
object o = _hashObjects[type];
if (o == null)
{
lock (_hashObjects)
{
//Still null? Need to check again because someone may
//have added it right before the lock.
o = _hashObjects[type];
if (o == null) //Now we know to create an instance.
{
try
{
//create object
o = Activator.CreateInstance(type,args);
//store it in the hashtable
_hashObjects[type] = o;
}
catch (Exception e)
{
throw new Exception("Factory could not create singleton object for type
" +
type.ToString() + ". " + e.Message);
}
}//end if
}//end lock
}//end if
return o;
}//end GetInstance method.
When this is executed with a SqlConnection as the type to instantiate, we
have a lockout (program stops responding). We know that the "lock"
statement is doing this. We're not locking the TYPE SqlConnection - we're
only locking a reference to the hashtable.
* Why does locking the hashtable reference cause a lockout?
* When we get this to work properly, when does an instance die?
{
object o = _hashObjects[type];
if (o == null)
{
lock (_hashObjects)
{
//Still null? Need to check again because someone may
//have added it right before the lock.
o = _hashObjects[type];
if (o == null) //Now we know to create an instance.
{
try
{
//create object
o = Activator.CreateInstance(type,args);
//store it in the hashtable
_hashObjects[type] = o;
}
catch (Exception e)
{
throw new Exception("Factory could not create singleton object for type
" +
type.ToString() + ". " + e.Message);
}
}//end if
}//end lock
}//end if
return o;
}//end GetInstance method.
When this is executed with a SqlConnection as the type to instantiate, we
have a lockout (program stops responding). We know that the "lock"
statement is doing this. We're not locking the TYPE SqlConnection - we're
only locking a reference to the hashtable.
* Why does locking the hashtable reference cause a lockout?
* When we get this to work properly, when does an instance die?