I came across some code like this.
public class ConnectionUtility
{
private static SqlConnection con;
public static SqlConnection GimmeConnection()
{
if(con==null)
con = new SqlConnection();
return con;
}
}
This is in an ASP.NET web application. Can one expect there to be race conditions where one request/page tries to open/close execute things on the connection and other request tries to do those things as well?
Two race conditions, one potentially harmless, one dreadful. There’s also a logical error.
The potentially harmless one is in the constructor logic of:
This can be harmless if you want to use a single object as an optimisation, but having a period where more than one is used is merely sub-optimal rather than wrong (not every race is the end of the world). It depends on just what
Thingis and how it’s used.The disastrous race is:
Because in this case the type is
SqlConnection, which is not thread-safe, so every single use of the property is a race that is courting disaster.The logical error is in having a singleton cache an object which is light to produce and which handles its own thread-safe pooling of the heavy part. Because of this pooling, you shouldn’t hold on to an
SqlConnectionany longer than absolutely necessary. Indeed, if you’ve a gap between one use and another (a bad smell in itself though), you should close it and re-open it again. This makes the thread-safe pooling thatSqlConnectionprovides for you, work at it most optimal between uses.