【问题标题】:How can I use timeout for try-catch?如何使用超时进行 try-catch?
【发布时间】:2015-10-19 23:49:56
【问题描述】:

我有一个这样的 oledbconnection 尝试捕获:

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;
}

当我无法连接数据库时,尝试捕获并返回v1 = 0。它可以正常工作,但是当连接等待时间过长(例如 30-40 秒)时,请尝试尝试连接和页面等待时间。

我为oledbconnection 尝试了Connect Timeout,但不起作用。

我需要使用try几秒,如果有问题,需要去catch。

我该怎么做?

【问题讨论】:

  • 你可以制作命令对象,然后使用OleDBCommand对象的CommandTimeOut属性来设置超时时间,或者设置数据库连接超时时间。
  • 你能给我举个例子吗?
  • string sQuery=你的查询在这里 SqlCommand cmd = new SqlCommand(sQuery, _Database.Connection); cmd.CommandTimeout = 0; int countRow = cmd.ExecuteNonQuery();
  • 注意:CommandTimeout 设置查询执行超时。

标签: c# asp.net try-catch oledbconnection


【解决方案1】:

假设您使用的是 .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
}

More info here

如果您被 .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.");
        }
    }
}

More info here

【讨论】:

  • 请注意,这是您需要超时的任何操作的一般答案。 OLE DB 连接应该支持有效的超时(在连接字符串中指定)!
【解决方案2】:

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

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

别忘了';'

【讨论】:

  • 我试过Connect Timeout=sec;,但它不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2010-12-15
  • 2011-07-09
  • 2016-06-15
  • 2021-11-09
  • 1970-01-01
相关资源
最近更新 更多