Counting undamaged tasks causes each task to run again.

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?

+1
c # async-await
Feb 25 '16 at 18:57
source share
1 answer

This is due to the multiple enumeration of your Select request.

To fix this, list the strength by calling the ToList() method. Then it will work correctly.

 var tasks = items.Select(item => { var clone = item.MakeCopy(); clone.Id = Guid.NewGuid(); return dbAccess.SaveAsync(clone); }) .ToList(); 

You can also take a look at these more detailed answers:

  • stack overflow

  • stack overflow .

+3
Feb 25 '16 at 19:22
source share



All Articles