I am creating a class that is used as an portal to read, insert and update values within a SQL Server database. This class implements the singleton design pattern, and therefore there will only be one instance of this class at any one time.
This class has individual methods for each action for the database values (read, write & delete), and each of those methods will open a SQLConnection, create, populate & execute the SQLCommand, and finally close the connection once completed.
Here is the example for adding a value:
public void AddGlossaryValue(string name, string value)
{
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
command = new SqlCommand(SQL_INSERT_COMMAND, connection);
command.Parameters.Add("@name", SqlDbType.NVarChar, 50);
command.Parameters.Add("@value", SqlDbType.NVarChar, 50);
command.Parameters["@name"].Value = name;
command.Parameters["@value"].Value = value;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
// handle exception - omitted in this example because it's irrelevant
}
finally
{
try
{
connection.Close();
}
catch (Exception) { }
}
}
I come from a Java background, where typically you would declare such methods as Synchronized, which means that the method can only be executed from one source at any one time. From my research into C#, it would appear that the typical method for achieving this is to lock and object.
My question is however, would that be recommended in a case such as above, and if so, where would the lock object be placed? Would it be immediately before the creation of the SQLConnection?
Many thanks
Why lock at all? You’re not using any shared resources in your dll code.
Just catch the sql error you’d likely see from a collision. If you insert something that’s already there, then you can do whatever happens to be appropriate at the time.
Save locking for shared resources in the code; things multiple threads could be accessing where you need to ensure determinant behavior. This code looks like you’re just firing something off to the database, you won’t be getting any behavior that you couldn’t easily explain by not using locks here.