Thirumalai
Thirumalai

Reputation: 121

Task returning wrong count of result in C#

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

Upvotes: 0

Views: 530

Answers (1)

Frank Bryce
Frank Bryce

Reputation: 8446

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

Upvotes: 1

Related Questions