C# OleDbConnection con set to timeout

2019-07-27 04:39发布

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

3条回答
Animai°情兽
2楼-- · 2019-07-27 05:28

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

查看更多
Anthone
3楼-- · 2019-07-27 05:39

@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.

查看更多
冷血范
4楼-- · 2019-07-27 05:39

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())
   {

   }
}
查看更多
登录 后发表回答