[sourcecode language="csharp"]
private sealed class MyDelegate : MulticastDelegate
{
public extern MyDelegate(object object, IntPtr method);
public extern virtual int Invoke(int x,int y);
public extern virtual IAsyncResult BeginInvoke(int x, int y
AsyncCallback callback, object object);
public extern virtual int Endinvoke((IAsyncResult result);
}
[/sourcecode]
This class consists of delegate constructor MyDelegate(..) , Invoke (..) , BeginInvoke(..) and EndInvoke(..)
- Delegate constructor runs when the delegate is instanciated. MyDelegate is instanciated as follows.
MyDelegate del;
This del reference is used to point a matching method.
- Invoke method accepts the same parameter list similar to the original function.
- BeginInvoke method requires all the in params , in-out params in the function definition. Furthermore, it needs AsyncCallback object and Object type reference.
calling BeginInvoke() causes to make an asynchronous call to the original method. The result is an IAsyncResult.
- After method execution completed, EndInvoke() is called passing all the in-out params , out params in the function definition. EndInvoke() requires the above IasyncResult.
Now let’s turn to asynchronius communication. When a delegate makes an asynchronius call to a method , the execution of the method does ont occur in the same thread. A separate thread is allocated for method execution. Caller thread waits until callie thread returns the result. These facts are justified by following code example.
[sourcecode language="csharp"]
using System;
using System.Threading;
public class Program {
public delegate int TheDelegate( int x, int y);
static int ShowSum( int x, int y ) {
int sum = x + y;
Console.WriteLine("Thread #{0}: ShowSum() Sum = {1}",
Thread.CurrentThread.ManagedThreadId, sum);
return sum;
}
public static void Main() {
TheDelegate d = ShowSum;
IAsyncResult ar = d.BeginInvoke(10, 10, null, null);
int sum = d.EndInvoke(ar);
Console.WriteLine("Thread #{0}: Main() Sum = {1}",
Thread.CurrentThread.ManagedThreadId, sum);
}
}
[/sourcecode]
No comments:
Post a Comment