首页 > 解决方案 > 如何停止处理时间过长的查询

问题描述

我有一个小程序,可以让学生测试他们在 ASP.Net 中构建的 SQL 查询并使用 SQL Server 数据库。问题是某些查询“挂起”控制台和 SQL Server。考虑到这一点,我想将执行时间限制为 10 秒或抛出异常。

现在代码看起来像这样:

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = TextBox1.Text; //Their query
        cmd.CommandType = CommandType.Text;
        cmd.CommandTimeout = 1;
        cmd.Connection = sqlConnection1;

        sqlConnection1.Open();
        try
        {
            GridView1.DataSource = cmd.ExecuteReader();
            GridView1.DataBind();
            int count = GridView1.Rows.Count;
            Label1.Text = count.ToString() + " Rows";
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
            GridView1.DataSource = null;
            GridView1.DataBind();
        }
        finally
        {
            sqlConnection1.Close();
        }

CommandtTimeout不是为我这样做,因为通常问题是查询是不断流式传输的行(主要是由于笛卡尔积运算)。

有没有办法在不遍历每一行的情况下停止查询中间执行?

标签: c#asp.netsql-server

解决方案


您可以使用线程来检查代码的超时

//Variables
string input;

//Code to run until time exceeds
Thread thread = new Thread(() => {
    input = Console.ReadLine();
});
thread.Start();

//Check if time exceeded
if (!thread.Join(TimeSpan.FromSeconds(10)))
{
    thread.Abort();
    throw new Exception("Time exceeded.");
}

推荐阅读