Reputation: 2918
One of our products is an application which allows the user to create and save projects, and within these projects, connections can be made to databases.
In our codebase we use ODBC and we open the connection with:
conn.Open()
where conn is an OdbcConnection object
.
If the connection fails, then it takes 15 seconds to do so. The upshot of this is that if we try to close a project that has an invalid connection within 15 seconds of opening it, then it takes 15 seconds to close. Which doesn't sound like much, but can be annoying.
So how can I cancel the conn.Open
call? The only thing I can think of at the moment is to put it on a separate thread and then Abort
the thread, but that doesn't sound like something I want to do. Is there a more controlled way of doing this?
Upvotes: 1
Views: 457
Reputation:
You can reduce the connection time out using for example 5 seconds:
var connection = new OdbcConnection(Program.Settings.ConnectionString);
connection.ConnectionTimeout = 5;
connection.Open();
If you don't want to reduce that, it is not possible to stop an open request, as I know:
You can try to do the openning in a thread and abort it after a special timeout or upon user request with a button for example.
c# Stop Thread with a button click
But I don't know if it will guarantee that the thread will be instantly stopped and what exception it may raise because of the underlying system. You should try with a thread, a task, a background worker or anything else.
Upvotes: 2