2017-02-14 191 views
0

我想了解连接超时和命令超时之间的关系,以及如何影响其他人。请考虑这个代码作为例子。SqlDataReader连接超时与命令超时

// 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有关。

+1

这应该回答你的问题:[SqlCommand.CommandTimeout和SqlConnection.ConnectionTimeout之间的区别是什么?](http://stackoverflow.com/questions/847264/what-is-the-difference-between-sqlcommand-commandtimeout -and-sqlconnection-conne) –

+0

我的问题有点不同。 SqlConnection.ConnectionTimeout用于打开连接的时间限制。我想强制读取所有记录的最长时间(while循环可以占用的总时间)。 – murtazat

+0

什么是你强加最大时间的理由?是什么让你得出结论:你需要实现最大超时? –

回答

2

我想设置超时的方式,我可以强制所有记录的最大超时。连接超时是否是一件好事?

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

。这意味着如果你再次调用Read(),它将会有另外30秒完成。

可能 - 这取决于每个读取的网络数据包的数量。你引用一个前一句说:

此属性是累计超时(适用于方法的调用过程中读取所有的网络数据包)的所有网络结果的命令执行或加工过程中读取。例如,在30秒超时后,如果Read需要两个网络数据包,则它有30秒钟的时间来读取两个网络数据包。

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

如果你想为while循环超时你需要的while循环中添加一个变量,并检查它:

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

我也将获得在包装的连接,命令的习惯,和using区块中的阅读器,以便在您完成操作后立即处理它们。