first many typos in my singleton. . .
here's the real code. . .
sealed public class MySingleton
{
static MySingleton _context;
string _data;
private MySingleton (){}
static public MySingleton Context
{
get
{
//lock the type for thread safety
lock( typeof(MySingleton))
{
//instance it if it has never been instanced
if (_context == null) _context = new MySingleton();
}
//return the global instance
return _context;
}
}
public string Data
{
get
{
return _data;
}
set
{
lock(this)
{
_data = value;
}
}
}
}
Locking the singleton type is slightly dangerous - it's a public
reference, effectively, so other things may lock the same reference.
I guess its something to worry about if for some stupid reason you expect
someone who uses your assembly to write a piece of code that is effectively:
lock(typeof(MySingleton)){ while (true){} };
But if I spent all my time trying to account for every moronic case in which
someone could break something, I wouldn't get anything done.
The fault here is not with the code of MySingleton but in the logic of the
use of MySingleton. The type was locked and they entered an infintite loop
condition.
Also if you prevent "lock(typeof(MySingleton))" from blocking access to
'Context', it would actually obfuscate the infinite loop condition, would it
not????
And wouldn't that make debugging harder if the moron created the condition.
For all intents and purposes, the application would appear to be working in
all other threads, and the fact that the loop never terminated would not be
apparent to the developer.
Am I wrong???