Home   Cover Cover Cover Cover
 

Common Type System (CTS)

Example "Sync/Async Delegate Call"

The example shows the synchronous and asynchronous use of delegates.
We define a delegate Adder for adding to Integer values and assign the static method Add to it.
Then we invoke the delegate method synchonously with the values 3 and 5, which means that we wait for the result of the computation.
Afterwards we start an asynchonous invocation. While the calculation is running, we can do different things in the Main method. At a later point in time, we check whether the calculation has completed and access the result.

SyncAsyncDelegate.cs
using System;
using System.Threading;

delegate int Adder (int a, int b);

public class SyncAsyncDelegateDemo {

  static int Add(int a, int b) { return a + b; }

  static void Main() {
    Adder a = new Adder(Add);

    // synchronous call of the delegate method
    Console.WriteLine("synchronous call:");
    
    int result = a(3,5);
    
    Console.WriteLine("3 + 5 = " + result);

    Console.WriteLine();
    
    // asynchronous call of the delegate method
    Console.WriteLine("asynchroner call:");
    
    IAsyncResult asyncCall = a.BeginInvoke(5, 8, null, null);

      // here one can do other things, e.g.
      Console.Write("calculating ");
      for (int i = 0; i < 3; i++) {
        Thread.Sleep(250);
        Console.Write(".");
      }
      Console.WriteLine();

    while (! asyncCall.IsCompleted)    // wait for completion of calculation
      Thread.Sleep(10);
    result = a.EndInvoke(asyncCall);
    
    Console.WriteLine("5 + 8 = " + result);
  }
}

Running this program yields the following output at the console:
>SyncAsyncDelegate.exe
synchronous call:
3 + 5 = 8

asynchroner call:
calculating ...
5 + 8 = 13