我经常使用数据填充数据读取器并以这种方式填充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...
});
OR
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
如何从 ForAll 获取数据。
任何人都可以帮助我理解其工作原理的代码段以及如何从 ForAll 获取数据,以及如何从 ForAll 填充我的用户界面。
另一个问题是我怎么知道哪个类是线程安全的。什么是线程安全的意思。一个人说datareader不是线程安全的。他怎么知道。
当一个人应该使用任务并行库时的另一个问题。 请指导。感谢
答案 0 :(得分:15)
您可以在MSDN文档中找到有关.NET基类库中每种类型的线程安全性的信息。大多数类型不线程安全。例如,SqlDataReader
不是线程安全的,因为它适用于与数据库的单个连接。
然而,Parallel.ForEach
是一个非常清晰的构造。您不能真正同时迭代多个线程的IEnumerable
,而Parallel.ForEach
不会这样做。虽然它会旋转多个线程并且那些多个线程会对给定的IEnumerable
进行迭代,但Parallel.ForEach
确保当时只有一个线程迭代可枚举的IEnumerator
。它假设处理元素比从枚举中获取项目花费更多时间。迭代可枚举是一个顺序操作。
这意味着即使基础数据源和SqlReader
的使用不是线程安全的,您仍然可以使用Parallel.ForEach
并行处理项目。遗憾的是,MSDN文档对此并不十分明确,但必须如此,因为从IEnumerator
方法返回的GetEnumerator()
实例从不是线程安全的。
当然,你必须确保给定的Action<T>
是线程安全的。
您可以使用以下程序查看此行为:
public static IEnumerable<int> GetNumbers()
{
for (int i = 0; i < 140; i++)
{
Console.WriteLine(
" Enumerating " +
i + " at thread " +
Thread.CurrentThread.ManagedThreadId);
yield return i;
}
}
static void Main(string[] args)
{
Console.ReadLine();
Parallel.ForEach(GetNumbers(), number =>
{
Console.WriteLine("Processing " + number +
" at thread " +
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1);
});
}