【问题标题】:SqlDataReader connection timeout vs command timeoutSqlDataReader 连接超时与命令超时
【发布时间】:2017-07-02 04:29:01
【问题描述】:

我想了解连接超时和命令超时之间的关系以及两者之间的关系。请将此代码作为示例。

// declare the SqlDataReader, which is used in
// both the try block and the finally block
SqlDataReader rdr = null;

// create a connection object
SqlConnection conn = new SqlConnection("someconnstr");

// create a command object
SqlCommand cmd = new SqlCommand("select * from dbo.mytable", conn);

try
{
    // open the connection
    conn.Open();

    // 1. get an instance of the SqlDataReader
    rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        // get the results of each column
        Guid Id = (Guid)rdr["Id"];
        string displayName = (string)rdr["Name"];

        // print out the results
        Console.WriteLine("{0}, {1}", Id, displayName);
    }

    Console.WriteLine("Reading done");
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

根据MSDN link,命令超时是所有读取的累积超时。这意味着如果您再次调用 Read(),它将有另外 30 秒的时间来完成。我想设置超时,以便我可以对所有记录施加最大超时。

连接超时对这样做有好处吗?在给定的示例中,如果我将连接超时设置为 120 秒并且 while 循环未在 120 秒内完成,它会引发超时错误吗?

此问题与Stackoverflow question 有关。

【问题讨论】:

  • 我的问题有点不同。 SqlConnection.ConnectionTimeout 用于打开连接的时间限制。我想规定读取所有记录的最长时间(while 循环可以花费的总时间)。
  • 您设置最长时间的理由是什么?是什么让您得出结论,您需要实施最大超时?
  • 作为单线程应用,需要从有while循环的方法快速返回读取所有记录。 CommandTimeout 似乎没有用,因为 while 循环的每次迭代都需要 30 秒才能完成。

标签: sql .net sql-server sqldatareader sqlconnection


【解决方案1】:

我想设置超时,以便我可以对所有记录施加最大超时。连接超时是否适合这样做?

否 - 连接超时是打开连接所需的最大时间。与建立连接后的操作无关。

。这意味着如果您再次调用 Read(),它将有另外 30 秒的时间来完成。

可能 - 这取决于每次读取需要多少网络数据包。你引用的那句话之前的句子是:

此属性是命令执行或结果处理期间所有网络读取的累积超时(对于在调用方法期间读取的所有网络数据包)。例如,在 30 秒超时的情况下,如果 Read 需要两个网络数据包,那么它有 30 秒的时间来读取这两个网络数据包。

有可能所有数据都可以在一个数据包中读取,而您只需要一次网络读取。

如果您希望 while 循环超时,您需要添加一个变量并在 while 循环中检查它:

DateTime maxTimeUtc = DateTime.UtcNow.AddSeconds(timeout)
while(rdr.Read())
{
    if(DateTime.UtcNow > maxTimeUtc)
    // do something
}

我还会养成将连接、命令和读取器包装在 using 块中的习惯,以便在您处理完它们后立即处理它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2019-09-13
    • 2021-09-06
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多