【发布时间】: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