C# OleDbConnection con set to timeout

2019-07-27 05:14发布

问题:

I have an app that queries an Access database and shows the data. I want the connection(con) to timeout after 2 minutes. Does anyone have any suggestions on how i can code this?

this is what i have in the beginning

OleDbConnection con;
OleDbDataReader dr;
OleDbCommand cmd;

con.Open();
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();

Thank you

回答1:

@Damith is close, but unfortunately the ConnectionTimeout property is read-only. You have to set the timeout in the connection string instead by using ... ;Connect Timeout=30;. Here's the documentation.



回答2:

Don't share the connection, create the connection when you need and wrap it by using block,

if you need to set the timeout, you can set by using ConnectionTimeout property in connection string (e.g. ".....;Connect Timeout=30"

using (OleDbConnection con = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
   con.Open();
   using (OleDbDataReader dr = cmd.ExecuteReader())
   {

   }
}


回答3:

Did you try Timeout parameters,

OleDbCommand.CommandTimeout Property - When you need time out during execution of the query

OleDbConnection.ConnectionTimeout Property - When you need time out whilemaking a connection