0

I am calling a Sync method Asynchronously using Task.Factory.StartNew. Once the Async completed, I need the result of it. I am running this task in parallel and combine each result in a result as below -

public List<Nomination> Submit(List<Nomination> nominations, string userEmail)
{
    var sublist = new List<Nomination>();
    int nSize = 5;
    var submitedList = new List<Nomination>();

    List<Task> tasks = new List<Task>();

    for (int index = 0; index < nominations.Count; index += nSize) // No nominations in a batch
    {
        sublist = nominations.GetRange(index, Math.Min(nSize, nominations.Count - index));

        //SubmitNomination is sync method which does some db operation and returns a List<Nomination>
        Task<List<DTO.FeedbackRequest>> task = Task.Factory.StartNew( () => { return SubmitNomination(sublist, userEmailName); });  

        Task cont = task.ContinueWith(submitted => {
            submitedList.AddRange(submitted.Result);
        });

        tasks.Add(cont);
    }
    Task.WaitAll(tasks.ToArray());

    return submitedList;
}

When I see the submitedList, I am getting the count of list is varying all the times. It suppose to be the count of nominations which got as input.

Can you please let me know how to solve this issue.

Many Thanks, Thirumalai M

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
Thirumalai
  • 121
  • 1
  • 11
  • You may need to protect the submitted list by locking it against change in other threads. – BugFinder Jun 14 '16 at 15:14
  • Be careful, [StartNew](http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html) and [ContinueWith](http://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html) can cause you to run code on the UI thread when you expect it to be running on a background thread, you should always pass in a `TaskSchedueller` to make sure it does not or use `Task.Run(` instead of `StartNew` – Scott Chamberlain Jun 14 '16 at 15:15
  • related: https://stackoverflow.com/questions/9877358/multiple-threads-adding-elements-to-one-list-why-are-there-always-fewer-items-i – Frank Bryce Jun 14 '16 at 15:19

1 Answers1

1

Two options

  1. Change submitedList to be a concurrent type, like ConcurrentBag<T>. In anticipation of your follow-up question, here's why you can't just use a concurrent list :)

  2. Put a lock around all of your submitedList operations

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56