❔ Avoiding "MySql connection is already in use"
so i have a bunch of C# scripts that all use the same api (mysql wrapper) but i came to notice that sometimes i get "connection in use" errors. by script i mean functions loaded through cs-script, but i guess you can think of it like a thread
to avoid this, i thought of using separate connections for every script. i thought this idea is what's called pooling, but apparently i was wrong. so how can i get by this issue?
5 Replies
you should be
new
ing up an SqlConnection
for every command, or serialized set of commands, you want to execute. Connection pooling happens underneath that hood, if you hahaqve it configured.
I.E. for every "script"but isnt that opening and closing a connection every time? unless im wrong, can you show me an example pls?
no
new SqlConnection()
does not necessarily create a new TCP connection to the database
that's what I mean when I say "Connection pooling happens underneath that hood"
if you have it configured
if a previously-used connection is still open, new SqlConnection()
will use that
if the maximum number of connections to the database are already open, and none of them is available, .OpenAsync()
will "block" until one of them becomes available, and use that
when previously-used connections become available, they will be cached and kept open for a certain amount of time, to allow for future reuse
if there is already a maximum number of connections being kept open for future reuse, connections will start being closed immediately
etc.
all of these behaviors are set via configuration, I.E. the connection stringSqlConnection.ConnectionString Property (System.Data.SqlClient)
Gets or sets the string used to open a SQL Server database.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.