delegate BeginInvoke of IAsyncResult

image_pdfimage_print

using System;
using System.Threading;

class AsyncDelegatesBlocked
{
public static int Add(int op1, int op2, out int result)
{
Thread.Sleep(3000);
return (result = op1 + op2);
}
public delegate int AddDelegate(int op1, int op2,out int result);

static void Main()
{
int result;
AddDelegate add = new AddDelegate(Add);

IAsyncResult iAR = add.BeginInvoke(6, 42, out result,null, null);

for (int i = 0; i < 10; i++) { Thread.Sleep(200); Console.Write("."); } iAR.AsyncWaitHandle.WaitOne(); add.EndInvoke(out result, iAR); Console.WriteLine("[Main] The result is {0}", result); } } [/csharp]

Async Delegates Callback

image_pdfimage_print
   
 

using System;
using System.Threading;
   
class AsyncDelegatesCallback
{
    public static int Add(int op1, int op2, out int result)
    {
        Thread.Sleep(1000); 
        return (result = op1 + op2);
    }
    public delegate int AddDelegate(int op1, int op2,
        out int result);
   
    public static void AnnounceSum(IAsyncResult iar)
    {
        AddDelegate add = (AddDelegate)iar.AsyncState;
   
        int result;
        add.EndInvoke(out result, iar);
   
        Console.WriteLine("[AnnounceSum] The result is {0}", result);
    }
   
    static void Main()
    {
        int result;
        AddDelegate add = new AddDelegate(Add);
        add.BeginInvoke(6, 42, out result, new AsyncCallback(AnnounceSum), add);
   
        Thread.Sleep(1000); 
    }
}

    


Async Delegate Invocation

image_pdfimage_print
   
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public delegate int BinaryOp(int x, int y);

class Program {
    static void Main(string[] args) {
        BinaryOp b = new BinaryOp(Add);
        IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null);

        while (!iftAR.AsyncWaitHandle.WaitOne(2000, true)) {
            Console.WriteLine("Doing more work in Main()!");
        }

        int answer = b.EndInvoke(iftAR);
        Console.WriteLine("10 + 10 is {0}.", answer);
    }

    static int Add(int x, int y) {
        Console.WriteLine("Add() invoked on thread {0}.", Thread.CurrentThread.GetHashCode());
        Thread.Sleep(5000);
        return x + y;
    }
}

    


two delegates and anonymous methods

image_pdfimage_print
   
  

using System;


public delegate void ADelegate(int param);
public delegate int BDelegate(int param1, int param2);

public class Starter {
    public static void Main() {
        ADelegate del = delegate(int param) {
            param = 5;
        };
    }

    public int MethodA() {
        BDelegate del = delegate(int param1, int param2) {
            return 0;
        };
        return 0;
    }
}