【问题标题】:Using a thread to timeout a ADO.NET query使用线程使 ADO.NET 查询超时
【发布时间】:2012-10-02 04:44:21
【问题描述】:

我需要对几种不同的 ADO.NET 连接类型(Sql 和 Oracle)运行查询。如果查询尚未完成,我希望能够在 X 秒后取消查询。我认为线程可能是解决此问题的好方法,所以我可以在 X 秒后杀死线程,如果它还活着的话:

var thread = new Thread((param) =>
{
    try
    {
        string connStr = "****";
        OracleConnection conn = new OracleConnection(connStr);
        try
        {                       
            conn.Open();
            Debug.WriteLine("Connection Open: " + DateTime.Now.ToLongTimeString());
            OracleCommand cmd = new OracleCommand(param as string, conn);
            Debug.WriteLine("Command Start: " + DateTime.Now.ToLongTimeString());
            OracleDataReader reader = cmd.ExecuteReader();
            Debug.WriteLine("Command End: " + DateTime.Now.ToLongTimeString());
            conn.Close();
            Debug.WriteLine("Connection Close: " + DateTime.Now.ToLongTimeString());
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Exception: " + ex.Message);
        }
    }
    catch (ThreadInterruptedException)
    {
        Debug.WriteLine("Cancel: " + DateTime.Now.ToLongTimeString());
    }
});

Debug.WriteLine("Start: " + DateTime.Now.ToLongTimeString());

thread.Start("begin dbms_lock.sleep(10); end;"); 
DateTime start = DateTime.Now;
while (thread.IsAlive)
{
    if (DateTime.Now > start.AddSeconds(5))
    {
        thread.Interrupt();
    }
}                

Debug.WriteLine("End: " + DateTime.Now.ToLongTimeString());

但是,这不会像我以前使用的其他代码那样使用 thread.Interrupt() 取消。

我怎样才能让它工作,或者有更好的方法来解决这个问题?

【问题讨论】:

  • 你必须先终止sql连接,这里显示stackoverflow.com/questions/7837739/…
  • 在我的场景中,我不太关心数据库上的实际查询,而更关心继续我的过程。我也没有必要的权限来终止查询。
  • 这段代码是在asp.net还是windows窗体中运行的?
  • 它是 ASP.NET MVC 应用程序的一部分。
  • 很好,然后使用 Web API 并为该 Web API 调用设置超时。

标签: c# multithreading ado.net


【解决方案1】:

创建一个 ASP.NET Web Api Controller 来封装您的 sql 查询,在您的 MVC 控制器中使用 HttpWebRequest 并为您对 api 的请求指定超时。 Web API 调用将返回一个包含查询结果的 JSON 对象,您需要在控制器中使用 JavaScriptSerializer.Deserialize 对其进行反序列化。

【讨论】:

  • 这个类在 .NET4 中可用吗?我似乎找不到 System.Web.Http dll。
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2017-04-24
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
相关资源
最近更新 更多