I am trying to spawn threads in a for each loop using a copy of the value in a dict.
My initial understanding was that the foreach
would create a new scope, and led to:
Dictionary<string, string> Dict = new Dictionary<string, string>() { { "sr1", "1" }, { "sr2", "2" } };
foreach (KeyValuePair<string, string> record in Dict) {
new System.Threading.Timer(_ =>
{
Console.WriteLine(record.Value);
}, null, TimeSpan.Zero, new TimeSpan(0, 0, 5));
}
which writes
1
2
2
2
instead of (expected):
1
2
1
2
So I tried cloning the kvp in the foreach:
KeyValuePair<string, string> tmp = new KeyValuePair<string, string>(record.Key, record.Value);
but that renders the same result.
I've also tried it with System.Parallel.ForEach
but that seems need values that are not dynamic, which is a bit of a train smash for my dictionary.
How can I iterate through my Dictionary with threads?