I wrote a code block, but I am not sure it is thread safe.
List<Task> tasks = new List<Task>(); foreach (KeyValuePair<string, string> kvp in result) { var t = new Task(async () => { int retries = 0; bool success = false; try { while (retries <= _maxRetries && !success) { await doSomething(kvp.Value); success = true; } } catch (Exception e) { retries++; } if (retries == _maxRetries) { //TODO: need to do smth about it } }); tasks.Add(t); t.Start(); } await Task.WhenAll(tasks); Can I rely on the fact that when the compiler sets the task he uses a safe value, meaning that as long as Im in the loop and the task haven't stated yet, the values set are ok?
Because, I think that after the first retry of the while loop, the kvp object won't be as he was when the task ran at first time.
If its in-fact not thread-safe, which I think it really isn't, how can it be fixed?