我喜欢 TPL 中 Parallel.For 和 Parallel.ForEach 扩展方法的简单性。我想知道是否有一种方法可以利用类似的东西,甚至可以利用稍微更高级的任务。
下面是 SqlDataReader 的典型用法,我想知道是否可行,如果可行,如何用 TPL 中的内容替换下面的 while 循环。因为读者无法提供固定数量的迭代,所以 For 扩展方法是不可能的,这让我无法处理我会收集的任务。我希望有人可能已经解决了这个问题并制定了一些使用 ADO.net 的注意事项。
using (SqlConnection conn = new SqlConnection("myConnString"))
using (SqlCommand comm = new SqlCommand("myQuery", conn))
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// Do something with Reader
}
}
}
最佳答案
您将很难直接替换那个 while 循环。 SqlDataReader不是 线程安全类,因此您不能直接从多个线程使用它。
也就是说,您可以处理您使用 TPL 读取的数据。这里有几个选项。最简单的可能是自己制作 IEnumerable<T>
适用于阅读器的实现,并返回包含您的数据的类或结构。然后您可以使用 PLINQ 或 Parallel.ForEach
并行处理数据的语句:
public IEnumerable<MyDataClass> ReadData()
{
using (SqlConnection conn = new SqlConnection("myConnString"))
using (SqlCommand comm = new SqlCommand("myQuery", conn))
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
yield return new MyDataClass(... data from reader ...);
}
}
}
}
获得该方法后,您可以通过 PLINQ 或 TPL 直接处理:
Parallel.ForEach(this.ReadData(), data =>
{
// Use the data here...
});
或者:
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
关于c# - 有没有办法将任务并行库 (TPL) 与 SQLDataReader 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3096727/