April 15th, 2010

ParallelExtensionsExtras Tour – #11 – ParallelDynamicInvoke

Stephen Toub - MSFT
Partner Software Engineer

(The full set of ParallelExtensionsExtras Tour posts is available here.) 

Delegates in .NET may have one or more methods in their invocation list.  When you invoke a delegate, such as through the Delegate.DynamicInvoke method, the net result is that all of the methods in the invocation list get invoked, one after the other.  Of course, in a parallel world we might want to invoke all of the methods in the invocation list in parallel instead of sequentially. The DelegateExtensions.cs file in ParallelExtensionsExtras provides an extension method on Delegate that does just that.

public static object ParallelDynamicInvoke(

    this Delegate multicastDelegate, params object[] args)

{

    return multicastDelegate.GetInvocationList()

           .AsParallel().AsOrdered()

           .Select(d => d.DynamicInvoke(args))

           .Last();

}

 

This ParallelDynamicInvoke extension method accepts the target multicast delegate as well as the params array to provide to the delegate invocation, just as with Delegate.DynamicInvoke:

public object DynamicInvoke(params object[] args);

 

ParallelDynamicInvoke uses the delegate’s GetInvocationList method to retrieve an array of all of the methods in the invocation list, each of which is represented as a Delegate.  Then, PLINQ is used to invoke each individual delegate, returning the last delegate’s result.

Author

Stephen Toub - MSFT
Partner Software Engineer

Stephen Toub is a developer on the .NET team at Microsoft.

0 comments

Discussion are closed.