Wednesday, February 15, 2012

Synchronous communication with delegates

Delegates are special types supported by the .NET Framework. It is a pointer to a function. A delegate pointing to a function has the same method signature as the function. Delegates are special classes. Delegates can be instanciated. Therefore we have delegate objects. A delegate object is a reference to one or more methods (static or instance).

In C# , delegate declaration as follows.

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

This delegate can be used as reference to any method which accepts two integer parameters and has the return type of int.

An example that uses MyDelegate delegate

[sourcecode language="csharp"]

namespace del
{
public delegate int MyDelegate(int num1,int num2);
class A
{
public int sum(int num1, int num2)
{
return num1 + num2;
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
MyDelegate del = a.sum;
Console.ReadLine();
}
}
}

[/sourcecode]

Here , delegate makes  a synchronous call to the function. In other words, function call is not asynchronous.
All the work related to calling sum(int a,int b) happens in the main thread.
Synchronous communication is based on single thread concept.
In above example, delegate calls sum(int a,int b)  and then the main thread blocks   until sum() method execution completes.   Therefore this thread can not execute any other code until method  execution is over.
It is obvious that synchronous communication is not preferred for User interfaces. In a user interface, UI responsiveness is highly considered. If all the work is maintained in a single thread, there is a chance for the UI to get stuck.

The following code verifies above function call is synchronous.  The resulting thread ids are similar.

[sourcecode language="csharp"]
namespace del
{
public delegate void MyDelegate();

class A
{
public void sum()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
}

class Program
{
static void Main(string[] args)
{
A a = new A();
MyDelegate del = a.sum;
del();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
//IAsyncResult rs = del.BeginInvoke(20, 10, null, null);
//string ans  = del.EndInvoke(rs);
//Console.WriteLine("Answer is {0}", ans);
Console.ReadLine();
}
}
}
[/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...