I have a multithreaded C# application where I need each thread to have an active connection. I can’t use connection pooling unless there is a way to use static connection to update/insert multiple tables accurately in a multithreaded app without using locks.When the number of connections is around 200, it is fine. The connection does not grow beyond this. But when I need 2200+ connections, the number of connections keep growing infinitely.
Code to create connection –
@"Data Source=Server-3-PC\SQLSERVER2012;Initial Catalog=****;Persist Security Info=True;User ID=****;Password=****;Pooling=false";
I am checking connections from SSMS using –
sp_who2
I found the answer. Creating connections and closing within Parallel loop is not reliable. The connections should always be created outside the loop, used inside and closed outside.
Thank you all for looking into it.
To better explain this, this works –
Connections are opened, used and closed just the way you want to. However, if you create connections inside the BuildHistoricalBarData method, it will keep growing.
The reason why pooling is not used here is ‘A’ is an array of items that point to different tables. Even if it had been same table, hCommandBars would be changed (by threads running in parallel) and you could never perform accurate insert/update actions without using locks. Locks would then slow it down.