进行连续ajax调用的正确方法是什么?

Leg*_*end 8 javascript asp.net iis ajax jquery

我有一些像这样的代码每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
    });
}
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,除了持续进行ajax调用16-20小时后,我从服务器返回错误:

超时已过期.从池中获取连接之前经过的超时时间.这可能是因为所有池连接都在使用中并且达到了最大池大小.

我启动了调试控制台,这是我观察到的:

AJAX调用正在被正确触发

在此输入图像描述

在16-20小时之前,有一些延迟增加的情况(这是Timeout第一次看到错误的地方)

在此输入图像描述

最后,代码设法遇到了一些瓶颈.每次通话和前端中断的延迟都会增加.在下面的蓝色箭头返回任何数据后没有电话.相反,它会抛出超时错误.

在此输入图像描述

我确信我做的事情从根本上是错误的.关于如何解决这个问题的任何想法?

编辑:服务器端代码

我的连接字符串:

Data Source={0};Initial Catalog={1};Integrated Security=True;MultipleActiveResultSets=true
Run Code Online (Sandbox Code Playgroud)

拉取记录的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

除非我遗漏了某些东西,否则我在使用该记录获取记录后关闭连接,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();
}
Run Code Online (Sandbox Code Playgroud)

小智 4

它看起来像是与数据库的连接太多的服务器端问题。你如何连接到数据库?使用后是否关闭连接?尝试在多次连接后关闭连接。