【发布时间】:2011-08-08 15:36:33
【问题描述】:
如果我没记错的话,当我在 using SqlConnection 块中使用 yield 时,我遇到了运行时异常。
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
yield reader[0];
}
// Call Close when done reading.
reader.Close();
}
当我将 yield 替换为一个 List 时,这些问题得到了解决,我在每次迭代中都添加了项目。
在 using StreamReader 块内时,我还没有发生同样的问题
using (var streamReader = new StreamReader(fileName))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
yield return line;
}
}
有什么解释为什么在前一种情况下发生异常而不是在后一种情况下发生异常?这种结构是否可取?
编辑要得到我过去所做的错误(早期处理),您应该调用下面的第一个方法:
IEnumerable<string> Read(string fileName)
{
using (var streamReader = new StreamReader(fileName))
{
return Read(streamReader);
} // Dispose will be executed before ReadLine() because of deffered execution
}
IEnumerable<string> Read(StreamReader streamReader)
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
yield return line;
}
}
使用其他延迟执行的方式也可以实现相同的错误,例如System.Linq.Enumerable.Select()
【问题讨论】:
-
你从 sql yield 得到什么异常?
-
如果您有反射器,请查看两个代码示例生成的代码。我应该阐明为什么一个投掷而一个不投掷。
-
@rossisdead 正如 LukeH 所指出的,一个可能的异常是 TimeoutException
-
@rossisdead 正如 jamietre 指出的那样,问题不是我在问题中编写代码时出现的问题,而是在我重构它时出现的问题,如我的问题编辑中所示
标签: c# .net exception using yield-return