Wednesday, March 11, 2015

Task parallelism in C# run multiple methods in parallel asynchronously

Version 4 of the .NET framework introduced the task parallel library, which has a Task (being an asynchronous operation). Task parallelism basically means multiple independent tasks (operations) running at the same time. The main benefit of using Task parallelism is a more efficient use of system resources and the extra methods available around tasks (such as cancellations and even scheduling).

One possible use of tasks is where you need to run a bulk action on a number of objects, for example changing a detail on each object. Looping through each change would mean that the previous operation must complete before calling the next, and where a service call is made to make the change, run time can add up. The following example shows how you can build an array of Tasks (each a separate operation call) and then run them all at once asynchronously.
var addressChanges = request.AddressChangesRequired;

if (addressChanges.Any())
    var tasks = new List<Task>();

    foreach (var addressChange in addressChanges)
        var memberNumber = addressChange.MemberNumber;
 var address = addressChange.Address;
        tasks.Add(Task.Run(() => EditMemberAddress(new EditMemberAddressRequest
            Address = address,
            MemberNumber = memberNumber

The reason member number and address are declared as variables instead of referencing the object in the for loop is that when the Tasks go to run, they will all reference the same object (the last one in the for loop).

EditMemberAddress is the operation which is begin called and the request object is what has been passed into the service (and is an array of address changes required).

No comments:

Post a Comment