我有一些这样的代码可以每 30 秒实时更新我页面上的图表:
var counter = 30;
$(function() {
prepare();
update();
});
function update() {
$("#timer").html("Refreshing in " + counter + " seconds...");
counter--;
if (counter == 0) {
counter = 30;
prepare();
}
setTimeout(update, 1000);
}
function prepare() {
$.ajax({
type: "POST",
url: "Service.asmx/GetPlotData",
contentType: "application/json; charset=utf-8",
success: OnSuccess, // this function plots the new data
error: OnError
});
}
除了在连续进行 ajax 调用 16-20 小时后,我从服务器返回一个错误,这似乎工作正常:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
我启动了调试控制台,这是我观察到的:
AJAX 调用被正确触发
在 16-20 小时之前,有一些延迟增加的情况(这是第一次看到 Timeout
错误)
最后,代码设法遇到了一些瓶颈。每次调用和前端中断的延迟都会增加。下面的蓝色箭头返回任何数据后没有调用。相反,它会抛出超时错误。
我确定我做的事情从根本上是错误的。关于如何解决此问题的任何想法?
编辑:服务器端代码
我的连接字符串:
Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true
拉取记录的代码:
try
{
string ConString = Constants.connString;
con = new SqlConnection(ConString);
cmd = new SqlCommand(sql, con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
// Add the records into an object
}
}
catch (Exception x)
{
// Send back some error text.
// This is what is giving out the Timeout error
}
finally
{
con.Close();
}
除非我遗漏了什么,否则我将在使用 con.Close()
获取记录后关闭连接,或者还有什么我需要做的吗?
编辑 2:将上面的代码更改如下。这是正确的吗?
try
{
string ConString = Constants.connString;
using (con = new SqlConnection(ConString))
{
cmd = new SqlCommand(sql, con);
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
// Add rows to object
}
}
}
catch (Exception x)
{
// Handle error
}
finally
{
con.Close();
}
最佳答案
这看起来像是与数据库的连接过多的服务器端问题。你如何连接到数据库?使用后是否关闭连接?连接数次后尝试关闭连接。
关于javascript - 进行连续 ajax 调用的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785821/