i often populate data reader with data and populate UI like this way
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
}
i was searching for the use of Task Parallel library with DataReader and found piece of code. it looks nice but objective is not very clear to me. so here is the code i got.
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 ...);
}
}
}
}
calling like
Parallel.ForEach(this.ReadData(), data =>
{
// Use the data here...
});
OR
this.ReadData().AsParallel().ForAll(data =>
{
// Use the data here...
});
how could i get the data from ForAll.
can anyone help me to understand the code snippet that how it works and how to get data from ForAll and how can i populate my UI from ForAll.
another question that how do i know that which class is thread safe or not. what does it mean thread safe. a person said datareader is not thread safe. how he knows.
another question when one should use task parallel library. please guide. thanks