【发布时间】:2012-08-14 19:11:24
【问题描述】:
我经常用数据填充数据读取器并以这种方式填充 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 搜索 Task Parallel 库的使用,并找到了一段代码。它看起来不错,但目标对我来说不是很清楚。这是我得到的代码。
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...
});
或
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
我如何从 ForAll 获取数据。
谁能帮我理解代码 sn-p 它的工作原理以及如何从 ForAll 获取数据以及如何从 ForAll 填充我的 UI。
另一个问题是我如何知道哪个类是线程安全的。这是什么意思线程安全。有人说数据读取器不是线程安全的。他怎么知道的。
另一个问题何时应该使用任务并行库。 请指导。谢谢
【问题讨论】:
-
如果您想在没有性能问题的情况下使用 TPL '只是为了使用它',那么我不会打扰。它让你的想法比你现在想象的更复杂。