c# - 如何停止处理时间过长的查询
问题描述
我有一个小程序,可以让学生测试他们在 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
不是为我这样做,因为通常问题是查询是不断流式传输的行(主要是由于笛卡尔积运算)。
有没有办法在不遍历每一行的情况下停止查询中间执行?
解决方案
您可以使用线程来检查代码的超时。
//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.");
}
推荐阅读
- python - 具有不同数量参数python的循环函数
- typescript - react-router withRouter 和 TypeScript 泛型
- mysql - 数据库视图:比较值和按日期分组
- python - 为什么 numba 不能编译这个 for 循环?
- javascript - 重定向后无法立即访问 cookie
- python - Django 2.1 模型观察者
- amazon-web-services - s3fs 在 /tmp 中缓存什么?
- java - 试图通过使用 Jframe 图标加载图片,框架加载但不是图片?有任何想法吗?
- mysql - 是否可以匹配由 INSERT ... SELECT 主键插入的新旧行
- node.js - 为什么 post 方法不做任何事情?