I have a problem stopping a Parallel for each loop.
I am iterating over a set of about 40.000 DataRows retrieved from a table, and I need to stop my loop immediately when I have 100 items in my resultset. The problem is that when I trigger the Stop method on the ParallelLoopState, the iteration is not stopped immediately, causing inconsistency in my resultset ( either to few or to many items).
Is there no way to make sure, that I kill all threads, as soon as I hit stop?
List<DataRow> rows = new List<DataRow>(dataTable.Select());
ConcurrentDictionary<string, object> resultSet = new ConcurrentDictionary<string, object>();
rows.EachParallel(delegate (DataRow row, ParallelLoopState state)
{
if (!state.IsStopped)
{
using (SqlConnection sqlConnection = new SqlConnection(Global.ConnStr))
{
sqlConnection.Open();
//{
// Do some processing.......
//}
var sourceKey = "key retrieved from processing";
if (!resultSet.ContainsKey(sourceKey))
{
object myCustomObj = new object();
resultSet.AddOrUpdate(
sourceKey,
myCustomObj,
(key, oldValue) => myCustomObj);
}
if (resultSet.Values.Count == 100)
state.Stop();
}
}
});