I have a section of C# code as follows. This code summarizes a column of 'doubles' in a DataTable :
var data = this.Db.ExecuteRead(query, this.Score.Name);
var time = 0.0;
foreach (DataRow row in data.Rows)
{
time += this.ParseDouble(row[0].ToString()) / MillisecondsPerMinute;
}
This code takes 4 seconds to execute. I wanted to speed it up, so I parallelized it as follows:
Parallel.ForEach(
data.AsEnumerable(),
row =>
{
time += this.ParseDouble(row[0].ToString()) / MillisecondsPerMinute;
});
This code takes 3 seconds to execute. It also causes collisions. I don't think a 'double' thread safe. This was expected. I then added a Mutex to make it thread safe:
Parallel.ForEach(
data.AsEnumerable(),
row =>
{
mut.WaitOne();
ptime += this.ParseDouble(row[0].ToString()) / MillisecondsPerMinute;
mut.ReleaseMutex();
});
This code is much slower. It takes 15 seconds to execute but produces accurate results. My question is, am I better off staying with the standard 'ForEach' here, or can I implement the multithreading in a better way?
For reference, here is the ParseDouble method:
protected double ParseDouble(string text)
{
double value;
if (!double.TryParse(text, out value))
{
throw new DoubleExpectedException();
}
return value;
}