Adrian Buzea
Adrian Buzea

Reputation: 836

Awaiting multiple tasks in a loop

I need to call a webservice multiple times because it has a limit of 100 objects returned per call, and I want to do this in parallel.

I'm making a task for each web service call and I stop when a task returns less than the limit of items, which means there are no more items to get.

public static async Task<List<Space>> GetSpacesByTypeParallel(SpaceType type, string ticket, int degreeOfParallelism)
{
    int offset = 0;
    int batchSize = degreeOfParallelism * RETURN_LIMIT;
    List<Space> spaces = new List<Space>();
    Task<List<Space>>[] tasks = new Task<List<Space>>[degreeOfParallelism];
    bool shouldContinue = true;
    while(shouldContinue)
    {
        for(int i = 0; i < degreeOfParallelism; i++)
        {
            tasks[i] = Task.Run<List<Space>>( () => GetSpacesAtOffset(offset + (i * RETURN_LIMIT), RETURN_LIMIT, ticket, null, type.ToString()) ); //GetSpacesAtOffset is a synchronous method
        }

        List<Space>[] result = await Task.WhenAll(tasks);

        foreach(List<Space> item in result)
        {
            spaces.AddRange(item);
            if(item.Count < RETURN_LIMIT)
            {
                shouldContinue = false;
            }
        }

        offset += batchSize;
    }
    return spaces;
}

I'm running this synchronously for testing purposes:

var spaces = Space.GetSpacesByType(SpaceType.Type1, ticket).Result;

However this always returns an empty list, but if I step through with the debugger it does do what it should.

What am I doing wrong ?

Upvotes: 0

Views: 1018

Answers (1)

Stephen Zeng
Stephen Zeng

Reputation: 2818

I believe it's caused by the closure variable. Try change it to

    for(int i = 0; i < degreeOfParallelism; i++)
    {
        var n = i;
        tasks[i] = Task.Run<List<Space>>( () => GetSpacesAtOffset(offset + (n * RETURN_LIMIT), RETURN_LIMIT, ticket, null, type.ToString()) ); //GetSpacesAtOffset is a synchronous method
    }

Upvotes: 3

Related Questions