[英]How can I use timeout for try-catch?
I have a try-catch for oledbconnection like this: 我有一个oledbconnection的try-catch,如下所示:
try
{
OleDbConnection Connection;
using (Connection = new OleDbConnection("Provider=MSDAORA.1;Data Source=DATABASE:1521/orcl//orcl1;Persist Security Info=True;Password=PASS;User ID=USER"))
{
Connection.Open();
v1 = 1;
Connection.Close();
}
}
catch (Exception)
{
v1 = 0;
}
When I can't connect database, try going to catch and return v1 = 0
. 当我无法连接数据库时,尝试捕获并返回
v1 = 0
。 It's working but when connection waiting so much(for example 30-40 seconds), try trying to connect and page waiting so much. 它正在工作,但是当连接等待了太多时间(例如30-40秒)时,请尝试尝试连接和页面等待那么多。
I tried Connect Timeout
for oledbconnection
but does not working. 我尝试了
oledbconnection
Connect Timeout
,但无法正常工作。
I need to use try for few secs, if any problem, need to go catch. 我需要使用try几秒钟,如果有任何问题,需要赶上。
How can I do that? 我怎样才能做到这一点?
Assuming you are using .net 4.5 then you can benefit the Task timeout and async await capabilities: 假设您使用的是.net 4.5,则可以受益于任务超时和异步等待功能:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
In case you are stuck with .net 3.5 or older: 如果您陷在.net 3.5或更旧的版本中:
using System.Threading;
class Program {
static void DoSomething() {
try {
// your call here...
obj.PerformInitTransaction();
} catch (ThreadAbortException) {
// cleanup code, if needed...
}
}
public static void Main(params string[] args) {
Thread t = new Thread(DoSomething);
t.Start();
if (!t.Join(TimeSpan.FromSeconds(30))) {
t.Abort();
throw new Exception("More than 30 secs.");
}
}
}
I don't see 'Connect Timeout={seconds};" in your connection string. As mentioned here 我没有看到“连接超时= {秒};”您的连接字符串中如前所述。 这里
the ConnectionTimeout property is read-only.
ConnectionTimeout属性为只读。 You have to set the timeout in the connection string instead by using Connect Timeout=30;
您必须在连接字符串中设置超时,而不是使用Connect Timeout = 30;
and don't forget ';' 而且不要忘记';'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.