ma.citi

A Coder's Blog

WCF client, sending multiple requests in parallel

A simple example of sending multiple requests (in parallel) to a web service, using WCF client and Task class.

    List<Request> requests = new List<Request>();

    //represents the batch size of requests sent in parallel
    int degreeOfParallelism = 3;

    using (var client = HttpClientFactory.Create())
    {
        client.Open();

        int i = 0;

        while (i < requests.Count) {

            //list of task to be run in parallel
            var tasks = new List<Task<Response>>();

            for(int y = 0; i < degreeOfParallelism; y++){

                int position = i + y;

                if (position >= requests.Count)
                    break;

                //adding task to task list
                tasks.Add(new Task<Response>(() => { return client.Send(requests[position]); }));
            }

            //starting all tasks
            tasks.ForEach(x => x.Start());

            //waiting all tasks to be completed
            Task.WaitAll(tasks.ToArray());

            //collecting/printing the responses received 
            tasks.ForEach(x => Console.WriteLine(x.Result));

            i += degreeOfParallelism;
        }
    }