如何在try-catch中使用超时?

phe*_*phe 2 c# asp.net oledbconnection try-catch

我有像这样的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;
}
Run Code Online (Sandbox Code Playgroud)

当我无法连接数据库时,请尝试捕获并返回v1 = 0.它正在工作但是当连接等待这么多时(例如30-40秒),尝试连接和页面等待这么多.

我试过Connect Timeoutoledbconnection,但不工作.

我需要尝试几秒钟,如果有任何问题,需要去抓.

我怎样才能做到这一点?

vez*_*kov 5

假设您使用的是.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
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里

如果您遇到.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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里


小智 0

我在连接字符串中没有看到“Connect Timeout={seconds};”。如此处所述

ConnectionTimeout 属性是只读的。您必须使用 Connect Timeout=30 在连接字符串中设置超时;

并且不要忘记“;”