I save a bunch of items in my database using async saves
var tasks = items.Select(item => { var clone = item.MakeCopy(); clone.Id = Guid.NewGuid(); return dbAccess.SaveAsync(clone); }); await Task.WhenAll(tasks);
I need to check how many times SaveAsync has been successful (it throws and throws out if something goes wrong). I use the IsFaulted flag to check tasks:
var successCount = tasks.Count(t => !t.IsFaulted);
The collection of elements consists of 3 elements, so SaveAsync should be called three times, but it will be executed 6 times. On closer inspection, I noticed that counting unexpected tasks with c.Count (...) forces each task to restart.
I suspect this has something to do with deferred LINQ execution, but I'm not sure why and how to fix it.
Any suggestion why I am observing this behavior and what would be the best pattern to avoid this artifact?
AstroSharp Feb 25 '16 at 18:57 2016-02-25 18:57
source share