9.2. Obtaining Return Values from Each Delegate in a Multicast Delegate
Problem
You have added multiple delegates to a single multicast delegate. Each of these individual delegates returns a value that is required by your application. Ordinarily, the values returned by individual delegates in a multicast delegate are lost—all except the value from the last delegate to fire, the return value of which is returned to the calling application. You need to be able to access the return value of each delegate that is invoked in the multicast delegate.
Solution
Use the GetInvocationList method as in Recipe 9.1. This method returns each individual delegate from a multicast delegate. In doing so, you can invoke each delegate individually and get its return value. The following method creates a multicast delegate called All and then uses GetInvocationList to fire each delegate individually. After firing each delegate, the return value is captured:
public static void TestIndividualInvokesReturnValue()
{
Func<int> myDelegateInstance1 = TestInvokeIntReturn.Method1;
Func<int> myDelegateInstance2 = TestInvokeIntReturn.Method2;
Func<int> myDelegateInstance3 = TestInvokeIntReturn.Method3;
Func<int> allInstances =
myDelegateInstance1 +
myDelegateInstance2 +
myDelegateInstance3;
Console.WriteLine("Invoke individually (Obtain each return value):");
foreach (Func<int> instance in allInstances.GetInvocationList())
{
int retVal = instance();
Console.WriteLine("\tOutput: " + retVal);
}
}This sample uses the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access