When I try to cancel an async ADO connection to some DB server that is offline (or not responding), the Cancel
method of the ADODB.Connection
object blocks for the set time-out period.
I do the async connection like this:
Set Connection = New ADODB.Connection
Connection.Provider = "SQLOLEDB"
Connection.ConnectionTimeout = 60
Connection.ConnectionString = "Initial Catalog=" & RTrim(DBName) & _
";Data Source=" & RTrim(DBServerName) & ";Integrated Security = SSPI"
Connection.Open , , , adAsyncConnect
And then later call the following to cancel/close the connection:
If (Connection.State And adStateConnecting) = adStateConnecting Then
' ==== CONNECTION BLOCKS HERE ======
Connection.Cancel
End If
If (Connection.State And adStateOpen) = adStateOpen Then
Connection.Close
End If
Set Connection = Nothing
Is there a way to not let the Cancel
method block?
I found my own solution at the end. Well, at least an acceptable workaround.
First I created a module that could cancel/close the connection in a timer (thanks to an idea from a Code Project article):
I then created a Connection surrogate class called
clsADOAsyncConn
I then update my original connection code to this:
The actual connection is then retuned by the
clsADOAsyncConn.ConnectComplete
event.The only known issue with this solution is that even though it helps prevent a block in normal execution of code, it still causes a block when the process exits (at least until the last pending connection(s) times out)