Showing posts with label Delegates. Show all posts
Showing posts with label Delegates. Show all posts

Saturday, November 21, 2009

Testing3

.NET,.NET Articles, .NET Assembly,.NET Code Samples,.NET Debugging,.NET Framework 3.5,.NET Framework 4.0,

.NET Interview, .NET Interview questions, .NET Questions,.NET Resources,.NET Tips and Tricks, .NET Tools, .NET Tutorials,.NET Video Tutorials,

Books,Collections, Connection Strings,Delegates, Design Patterns ,Interview, Interview Questions, Threading , Visual Studio, VSS , Webcasts

Wednesday, February 04, 2009

Call method Asynchronously using delegate in C#

The .NET Framework enables you to call any method asynchronously. To
do this you define a delegate with the same signature as the method
you want to call; the common language runtime automatically defines
BeginInvoke and EndInvoke methods for this delegate, with the
appropriate signatures.

The BeginInvoke method initiates the asynchronous call. It has the
same parameters as the method that you want to execute
asynchronously, plus two additional optional parameters. The first
parameter is an AsyncCallback delegate that references a method to be
called when the asynchronous call completes. The second parameter is
a user-defined object that passes information into the callback
method. BeginInvoke returns immediately and does not wait for the
asynchronous call to complete. BeginInvoke returns an IAsyncResult,
which can be used to monitor the progress of the asynchronous call.

The EndInvoke method retrieves the results of the asynchronous
call. It can be called any time after BeginInvoke. If the
asynchronous call has not completed, EndInvoke blocks the calling
thread until it completes. The parameters of EndInvoke include the
out and ref parameters of the method that you want to execute
asynchronously, plus the IAsyncResult returned by BeginInvoke.

Below is the Class “AsyncDemo” which demonstrate how to call
method in async mode.


class AsyncDemo

{


//This will point to any method which has two integer arguments.

private delegate int MyDelegate(int input1, int input2);

//Variable of above mention delegate.


MyDelegate mDeleg;

private int Calc(inta, int b)

{


System.Threading.Thread.Sleep(new System.TimeSpan(0, 0, 0, 5, 0));

return a + b;


}


private void CalcCallback(IAsyncResult ar)


{


int answer = mDeleg.EndInvoke(ar);

string sss = ar.AsyncState as string;

}





public void MyDemo()

{


mDeleg = new MyDelegate(Calc);

AsyncCallback callback = new AsyncCallback(CalcCallback);

int input1 = 111;

int input2 = 222;


string strResult = null;

mDeleg.BeginInvoke(input1, input2, callback, "Tejas");

}

}

Below is the image of the above class in the assembly.Shows how BeginInvoke() and EndInvoke() is generated by CLR.

Friday, May 23, 2008

Covariance and Contra-variance Delegate

Delegates are pointers to the method to be invoked. In C# 2.0 new features has been introduced known as Covariance and Contra-variance.

Before we proceed consider we class hierarchy like as below

class A{}

Class B: A{}

In our program we have delegate like below

class Program
{
        public delegate A MyDelegate();
        static void Main(string[] args)
{
            MyDelegate delObj = new MyDelegate(CreateObject);
A a = delObj();
}
        public static A CreateObject()
{
return new A();
}
}

Covariance: C# 2.0 provides us flexibility that now when instantiating a delegate the specified method may also have the return type which is the derived form of the return type specified by delegate. For example, now we can instantiate the MyDelegate with a method whose return type is B.

class Program
{
        public delegate A MyDelegate();

static void Main(string[] args)
{
            MyDelegate delObj = new MyDelegate(CreateObject);       
A a = delObj();
}
        public static B CreateObject ()
{
return new B();
}
    }
This is called the covariance. It is not a problem for a compiler also because B (being sub-class of A) can easily be casted to A.
Note: When this functionality was not present in .net 1.x at that time developer need to define two delegates with different return type.


Contravariance:

Suppose we have two classes A and B with A being the parent class of B like

    class A
{
public void ADisplay()
{
Console.WriteLine("A is called...");
}
}
    class B : A
{
public void BDisplay()
{
Console.WriteLine("B is called...");
}
 }
And in our program we defined a delegate which takes a parameter of type B then with C# 1.x, we can instantiate the delegate whose signature is exactly same as that of MyDelegate() that is which takes an object of type B.

 class Program
{
        public delegate void MyDelegate(B bObj);
static void Main(string[] args)
{
            MyDelegate delObj = new MyDelegate(Fun);       
delObj(new B());
Console.ReadLine();
}

public static void Fun(B bObj)
{
bObj.BDisplay();
        }
}

When we run the program it prints the expected output

B is called...

But in C# 2.0, thanks to the contra-variance feature, we can also instantiate the delegate with a method which accepts the parameter of parent type of the type specified by the delegate. For instance in our example, we can instantiate MyDelegate() with a method which accepts an object of type A!

class Program
{
        public delegate void MyDelegate(B bObj);
static void Main(string[] args)
{
            MyDelegate delObj = new MyDelegate(MoreFun);       
delObj(new B());
Console.ReadLine();
        }
        public static void Fun(B bObj)
{
            bObj.BDisplay();
        }
        public static void MoreFun(A aObj)
{
            aObj.ADisplay();
        }
    }



When we run the program, the output is
A is called...


In fact, it is possible because the method being referred MoreFun() accepts an object of type A but the delegate accepts an object of type B. Since, B is a sub-class of A it is possible to cast an object B to type A and pass it to MoreFun().

Anyhow, covariance and contra-variance are really very useful features and it is really good to see these features added to the C# 2.0 programming language.