简体   繁体   中英

How can I cancel OdbcConnection.Open() in case it takes too long?

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?

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:

https://referencesource.microsoft.com/#System.Data/fx/src/data/System/Data/Odbc/OdbcConnection.cs,415c9a2f8c368e8f

https://github.com/mono/mono/blob/master/mcs/class/referencesource/System.Data/System/Data/Odbc/OdbcConnection.cs

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

Button Click to stop a test

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM