我经常用数据填充数据读取器并像这样填充 UI
using (SqlConnection conn = new SqlConnection("myConnString"))
using (SqlCommand comm = new SqlCommand("Select * from employee where salary<5000", conn))
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// here i populate my employee class
}
}
// here i update UI
}
我正在搜索任务并行库与 DataReader 的使用并找到了一段代码。它看起来不错,但目标对我来说不是很清楚。这是我得到的代码。
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 ...);
}
}
}
}
打电话像
Parallel.ForEach(this.ReadData(), data =>
{
// Use the data here...
});
OR
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
我怎样才能从中获取数据ForAll.
任何人都可以帮助我理解代码片段,它是如何工作的以及如何从中获取数据ForAll我如何填充我的用户界面ForAll.
另一个问题是我如何知道哪个类是线程安全的。线程安全是什么意思。有人说 datareader 不是线程安全的。他怎么知道。
何时应该使用任务并行库的另一个问题。
请指导。谢谢