You're going to have difficulty replacing that while loop directly. SqlDataReader is not
a thread safe class, so you cannot use it directly from multiple threads.
That being said, you could potentially process the data you read using the TPL. There are a few options, here. The easiest might be to make your own IEnumerable<T>
implementation that works on the reader, and returns a class or struct containing your data. You could then use PLINQ or a Parallel.ForEach
statement to process your data in 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 ...);
}
}
}
}
Once you have that method, you can process this directly, via PLINQ or TPL:
Parallel.ForEach(this.ReadData(), data =>
{
// Use the data here...
});
Or:
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…