I am making my first attempt to play with new Tasks, but something happens that I do not understand.
Firstly, the code is pretty straight forward. I pass a list of paths to some image files and try to add a task to process each of them:
public Boolean AddPictures(IList<string> paths) { Boolean result = (paths.Count > 0); List<Task> tasks = new List<Task>(paths.Count); foreach (string path in paths) { var task = Task.Factory.StartNew(() => { Boolean taskResult = ProcessPicture(path); return taskResult; }); task.ContinueWith(t => result &= t.Result); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); return result; }
I found that if I just let it run, say, a list of three paths in unit test, all three tasks use the last path in the specified list. If I pass (and slow down the processing of the loop), each path from the loop is used.
Can someone explain what is happening and why? Possible workarounds?
multithreading c # task-parallel-library
Wonko the Sane Jan 13 '11 at 19:27 2011-01-13 19:27
source share