I'm using a threadpool to do some heavy processing and also bits of sql. Currently I open sql connections when I need them, run a query and then close them. This works fine. The application has been running with no issues. As more work is being done by this application it's using more threads. More threads mean more opening/closing of SQL connections. In SQL 2005 this actually hammers the server. My test server is doing around 175 transactions / sec. Approx 150 of these are being run in the master database and are "ValidateSQLLogin".
I'm going to change the app so that each thread has it's own connection and then this connection is passed around the thread.
So my question is:
If a SQL connection object is created locally in a thread and is then passed by ref to a static function of another class would this be unsafe?
void ThreadA()
{
SqlConnection a = new SqlConnection(....);
MyStaticClass.DoStuff(ref a);
}
void ThreadB()
{
SqlConnection b = new SqlConnection(....);
MyStaticClass.DoStuff(ref b);
}
static void MyStaticClass.DoStuff(ref SqlConnection sql)
{
// Do stuff with sql
}
My initial thought is that it would be unsafe as 10 threads could all call the same static function at the same time, each passing their own connection object.
Previously the static functions opened their own connections and closed them when they were done.
If it is unsafe whats the best method to work round this. I need to try and minimize open/close of Sql connections.
Thanks
Gareth