Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If the type of the delegate is known, you can directly call their BeginInvoke ans store the IAsyncResults in an array to wait and end the calls. Note that you should call EndInvoke in order to <a href="http://msdn.microsoft.com/en-us/magazine/cc164036.aspx#S3" rel="nofollow noreferrer">avoid potential resource leaks</a>. The code relies on the fact that EndInvoke waits until the call is finished, so that no WaitAll is required (and, mind you, <a href="http://www.albahari.com/threading/part2.aspx#_WaitAny_WaitAll" rel="nofollow noreferrer">WaitAll has several issues</a> so that I'd avoid its use).</p> <p>Here is a code sample, which is at the same time a simplistic benchmark for the different approaches:</p> <pre><code>public static class MainClass { private delegate void TestDelegate(string x); private static void A(string x) {} private static void Invoke(TestDelegate test, string s) { Delegate[] delegates = test.GetInvocationList(); IAsyncResult[] results = new IAsyncResult[delegates.Length]; for (int i = 0; i &lt; delegates.Length; i++) { results[i] = ((TestDelegate)delegates[i]).BeginInvoke("string", null, null); } for (int i = 0; i &lt; delegates.Length; i++) { ((TestDelegate)delegates[i]).EndInvoke(results[i]); } } public static void Main(string[] args) { Console.WriteLine("Warm-up call"); TestDelegate test = A; test += A; test += A; test += A; test += A; test += A; test += A; test += A; test += A; test += A; // 10 times in the invocation list ParallelInvoke.Invoke(test, "string"); // warm-up Stopwatch sw = new Stopwatch(); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Profiling calls"); sw.Start(); for (int i = 0; i &lt; 100000; i++) { // ParallelInvoke.Invoke(test, "string"); // profiling ParallelInvoke Invoke(test, "string"); // profiling native BeginInvoke/EndInvoke } sw.Stop(); Console.WriteLine("Done in {0} ms", sw.ElapsedMilliseconds); Console.ReadKey(true); } } </code></pre> <p>On my very old laptop this takes 95553 ms with BeginInvoke/EndInvoke vs. 9038 ms with my ParallelInvoke approach (MS .NET 3.5). So this approach scales <em>not</em> well compared to the ParallelInvoke solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload