Showing posts with label Delegate. Show all posts
Showing posts with label Delegate. Show all posts

Tuesday, December 13, 2011

How to create custom Application Domain?



Each .NET application by default creates one application domain. The default application domain created by CLR automatically when process (application) starts. Application domain is the runtime unit of isolation in which runs .net application in managed memory boundary. Application domain created under process and process can have one or more application domains. See below figures.

Process with single Application Domain


 Process with multiple Application Domains



Creating Custom Application Domains

AppDomain class is provided by .Net to create custom application domain. AppDomain.CreateDomain and AppDomain.Unload methods are provided to create and destroy custom application domain. Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       }     
}



In above example, AppDomain.CreateDomain method creates new application domain named “My Domain” and AppDomain.Unload method unloads or removes "My Domain". DoCallBack method is used to execute action on another application domain. The HelloMethod is static so DoCallBack (CrossAppDomainDelegate) delegate is referencing a static method.

AppDomain also provides ExecuteAaasembly method which will execute an assembly file.

AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.ExecuteAssembly("WPFApplication1.exe");
Console.ReadLine();
AppDomain.Unload(appDomain);

When you create a new application domain within your current process, CLR keeps isolated one application domain from other. So each application domain has its own separate memory and objects which can’t clash with other application domain.

Sharing Data between application domains

We can share data between application domains using named slots. AppDomain instance provides SetData method to set data as name and data pair. While the GetData method retrieves an object (data) based on given name. Below are the signatures of both the methods. 

public void SetData(string name, object data);
public object GetData(string name);

Let’s have a look on below code.

public class MyClass
{
       public static void Main()
       {
              AppDomain appDomain = AppDomain.CreateDomain("My Domain");
appDomain.SetData("AppDomainOwner", "Mitesh Sureja");
appDomain.DoCallBack(new CrossAppDomainDelegate(HelloMethod));
Console.ReadLine();
AppDomain.Unload(appDomain);
       }
       public static void HelloMethod()
       {
              Console.WriteLine("Hello from " + AppDomain.CurrentDomain.FriendlyName);
       Console.WriteLine("Created By " + AppDomain.CurrentDomain.GetData("AppDomainOwner"));
       }     
}


As shown in above example, SetData method set name as “AppDomainOwner” and data as “Mitesh Sureja”. While GetData method retrieves data as an object based on given name.

Another way to share data between multiple application domains is using Remoting.

Hope you liked this post related to application domain. Please feel free to write your comments/feedback in comments section below.

See Also - 

Wednesday, December 7, 2011

System.Threading.Timer vs. System.Timers.Timer



Timer provides mechanism to execute method at specific intervals. Dotnet Framework provides two types of Timers.

1.        System.Threading.Timer

System.Threading.Timer is easiest and simplest to implement. We need to provide delegate to constructor of timer object. We also need to provide other information like state, duetime and period while creations of Timer object. Below is the Timer class constructor signature.

public Timer(TimerCallback callback, object state, int dueTime, int period);

First parameter is callback method which will repeatedly call at specified period. Second parameter accepts value as an object to the method if you want to pass. Third parameter accepts due time after that time your method will start executing. The last parameter is period which will call method repeatedly at specified period. Let’s have a look on below code.

using System.Threading;
public class MyClass
{
    public static void RunSnippet()
    {
       Timer t1 = new Timer(HelloMessage, null, 2000, 500);
       Console.ReadLine();
       t1.Dispose();
    }
    public static void HelloMessage(object obj)
    {
        Console.WriteLine("Hello World...");
    }
}


As per above example the HelloMessage will get called every 500ms after 2000ms have elapsed. The dispose method will stop the timer as well remove from memory. Timer internally uses ThreadPool to execute callback method.

2.        System.Timers.Timer

System.Timers.Timer is almost similar to System.Threading.Timer. System.Timers.Timer calls event repeatedly on certain interval. This timer also known as server based timer. This timer is used in MultiThreading to call Elapsed events. System.Timers.Timer provides more properties and methods compare to System.Threading.Timer. Below are some important properties of System.Timers.Timer.

Interval     – Specifies the interval time to raise the elapsed event.
Elapsed    – Specifies event (callback delegate)
Enabled    – Used to start/stop timer.
Start        – Used to start timer.
Stop         – Used to stop timer.

using System.Timers;

public class MyClass
{
   public static void RunSnippet()
   {
        Timer t1 = new Timer();
        t1.Interval = 500;
        t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
        t1.Start();
        Console.ReadLine();
        t1.Stop();
        Console.ReadLine();
        t1.Dispose();
   }
   static void t1_Elapsed(object sender, ElapsedEventArgs e)
   {
        Console.WriteLine("Hello World...");
   }
}


The t1_Elapsed event will automatically get called every 500ms after starting t1 timer. 


See Also - 


Friday, September 30, 2011

Working with Thread Pool in C# (Dotnet)


What is Thread Pool?

Thread pool is collection of Threads which can be used to perform different tasks in background. All threads available in Thread Pool can be used as Background ThreadBackground thread runs asynchronously in background and remains main thread active (UI will be responsive). When you create and start Thread it takes some significant time to create it in memory, instead Thread pool can be used. Thread pool manages overhead to create and recycle threads. Thread pool keeps watch on total number of worker threads are running asynchronously if it reached to its limit then threads are queued up and wait until any of the thread finishes its task from Thread pool. This way thread pool reuses the threads and avoids the cost of creating new threads each time. We can explicitly set Max and Min limit of Threads that Thread Pool creates by calling ThreadPool.SetMaxThread and ThreadPool.SetMinThread methods respectively.


How to work with Thread Pool?

There are number of ways to use thread pool in your application.

1.       ThreadPool.QueueUserWorkItem
2.       Task Parallel Library (PLINQ)
3.       Delegates (asynchronous delegates)
4.       BackgroundWorker


ThreadPool.QueueUserWorkItem

Thread pool class provides facility to queue items using QueueUserWorkItem method. This method accepts WaitCallBack delegate. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    ThreadPool.QueueUserWorkItem(DoSomething);
}

private static void DoSomething(object x)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above code, I have used ThreadPool.QueueUserWorkItem method to request queue for my task from Thread pool. This methods queue thread requested and allocate thread from thread pool class if available. This method accepts WaitCallBack delegate and as per delegate signature it accepts one argument of object type so I have added one argument to DoSomething method. In above code I have not passed any argument to DoSomething method so it will take null as default. Another interesting thing is you can check whether the thread is from Thread pool or not using Thread.CurrentThread.IsThreadPoolThread. This property returns true if the thread is from Thread pool and returns false if not.


Task Parallel Library (PLINQ)

Task Parallel Library is introduced with Dotnet Framework 4.0. We can use Task class of TPL to enter into Thread Pool. Task class provides Factory to start new task from Thread pool. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    Task.Factory.StartNew(DoSomething);
}

private static void DoSomething()
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above code, Task class used to start new thread from Thread pool. Task.Factory.StartNew method used to start thread from thread pool. StartNew method accepts delegate action as parameter.


Asynchronous Delegate

Asynchronous delegate internally uses thread from Thread Pool class. You can pass arguments and return value from delegate method. Let’s have a look on below code.

public static void Main()
{
    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());

    Func<string, int> MyDelegate = DoSomething;
    MyDelegate.BeginInvoke("Hello", null, null);
}

private static int DoSomething(string x)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
    return 0;
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool

In above example, I made few changes in existing example and used asynchronous delegate. When you call BeginInvoke method of delegate it executes task in parallel thread and the thread will be pooled from ThreadPool class. I have created one Func<> delegate with string argument and integer as return type. This method is being executed in background thread of Thread pool class.


BackgroundWorker

Background worker class also uses thread from Thread pool to perform task in background. For more information about background worker you can go through my post on BackgroundWorker. Let’s have a look on below code
.
BackgroundWorker workerThread;

public static void Main()
{
    workerThread = new BackgroundWorker();
    workerThread.DoWork += new DoWorkEventHandler(workerThread_DoWork);
    workerThread.RunWorkerCompleted += new
        RunWorkerCompletedEventHandler(workerThread_RunWorkerCompleted);

    Console.WriteLine("Calling from Main Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    workerThread.RunWorkerAsync();  
}
private void workerThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Console.WriteLine("Worker thread completed.");
}

private void workerThread_DoWork(object sender, DoWorkEventArgs e)
{
    Console.WriteLine("Calling from Thread Pool's Thread...");
    Console.WriteLine("Is Thread Pool Thread : " +
        Thread.CurrentThread.IsThreadPoolThread.ToString());
    Console.WriteLine("Hi, I am using Thread Pool");
}

Output
Calling from Main Thread...
Is Thread Pool Thread : False
Calling from Thread Pool's Thread...
Is Thread Pool Thread : True
Hi, I am using Thread Pool
Worker thread completed.

As per above code, I have created one instance of BackgroundWorker class. I have also attached DoWork and RunWorkerCompleted methods to backgroundworker instance. So when I call RunWorkerAsync method of worker thread it will be executed on separate thread in background and thread will be pooled form Thread pool. When worker thread completes it will notify user with completed state.

As explained above, these all are the ways to use threads from Thread pool.

Hope you liked this post. Please leave your comments and feedback in comments section of this post.

See also –

Friday, August 26, 2011

Delegate vs. Interface


In this post I will explain some distinct features of delegate and interface.

All of you might aware about delegate and interface functionality in .Net. The similar kind of functionality can be achieved using both delegate and interface but both have their unique features too. So the question is when to use interface and when to use delegate?

Let’s start understanding using simple example.

Example 1 - Using interface

public interface IMyInterface
{
     void MyMethod(string name);
}
public class MyClass : IMyInterface
{
     public void MyMethod(string name)
     {
         Console.WriteLine("Hello " + name);
     }
}
public static void Main()
{
IMyInterface iCall = new MyClass();
iCall.MyMethod("Mitesh"); //Output: Hello Mitesh
}

Example 2 - Using delegate

public class MyClass
{
    public void MyMethod(string name)
    {
        Console.WriteLine("Hello " + name);
    }
}
public delegate void MyDelegate(string name);
public static void Main()
{
MyClass cls = new MyClass();
       MyDelegate d = cls.MyMethod;
       d("Mitesh"); //Output: Hello Mitesh
}

Output of example 1 and 2 both are same but both example uses different concept example 1 is using Interface and example 2 is using delegate.

Let’s understand when to use Delegate and when to use Interface?

Use Delegate when -

  • You need to use multicast capability.
  • You want to wrap static methods.
  • Delegate can be used from anywhere in the scope they visible.
  • An event pattern is used.
  • You want to use anonymous methods.


Use Interface when -

  • A class needs only one implementation of method.
  • You want to use inheritance feature because interface can inherit from other interface.
  • You want to avoid method pointers overhead. When you call method using delegate it first scan through before executing it but in case of interface it directly calling method. It has some significance performance improvements.
  • Multiple kind of events are supported and need to implements all of them

See also


Thursday, August 18, 2011

Covariance and Contravariance in C# 4.0


What is covariance and contravariance?

Covariance and contravariance allows implicit reference conversion for array, delegate and generic type argument. For e.g. type A is base class and type B is subclass of type A so a = b called as covariance and b=a called as contravariance. Let’s understand by simple example.

Simple covariance example

public class A { }
public class B : A{ }

A a = new A();
B b = new B();

a = b; //covariance
b = a; //contravariance (gives Compile time error)

In above example a=b is called as covariance while b = a called as contravariance. The last line gives compile time error because type ‘a’ can’t convert to type ‘b’.

Array covariance

Arrays supports covariance let’s have a look on below code.

string[] str = new string[10];
object[] obj = str;   //covariance

In above code string array is assigned to object array. Which works fine because string array can implicitly converted to object array.

obj[1] = new object(); //throw runtime error
But when new object assigned to obj then it will throw a run time error.

Generic Interface – Covariance and Contravariance (C# 4.0)

C# 4.0 supports covariance and contravariance for generic interfaces.

Covariance

To support covariance for generic interface need to add ‘out’ modifier as argument with T in interface. The out modifier allows interface as covariance. 

Let’s have a look on below code.

public class A { }
public class B : A{ }
public class D<T> : IMyInterface<T>
{
}

interface IMyInterface<out T> { }

D<B> db = new D<B>();
IMyInterface<A> ia = db; //Covariance (only compiles in C# 4.0)

In above code snippet, Interface of type a allows to reference type b which is possible by adding out modifier to interface.

Contravariance

Type is contravariance when you convert in the reverse direction like type b = a. The ‘in’ modifier should be passed as parameter with interface and it allows interface as contravariant. Let’s have a look on below code.

public class A { }
public class B : A{ }
public class D<T> : IMyContraInterface<T>
{
}
interface IMyContraInterface<in T> { }

D<A> da = new D<A>();
IMyContraInterface<B> ib = da; //Contravariance (only compiles in C# 4.0)

In above example type a is assigned to type b which is possible because ‘in’ modifier passed to interface. The out keyword marks a type parameter as covariant and in keyword marks a type parameter as contravariant.

Generic delegate – Covariance and Contravariance (C# 4.0)

C# supports covariance and contravariance for C# generic delegates also similar to generic interface. To support covariance for generic delegate need to add out modifier with T in interface. The out modifier allows delegate as covariance and the in modifier allows delegate as contravariance. Let’s have a look on below code.

public class A { }
public class B : A{ }

delegate T MyCoVariantDelegate<out T>();
delegate void MyContraVariantDelegate<in T>(T arg);

MyCoVariantDelegate<B> b = () => new B();
MyCoVariantDelegate<A> a = b; //Covariance (only compiles in C# 4.0)

MyContraVariantDelegate<A> a = (a2) => Console.WriteLine("hello");
MyContraVariantDelegate<B> b = a; //Contravariance (only compiles 
                                    in C# 4.0)


In above code snippet, delegate type a allows to reference type b and similar delegate type b allows to reference type a which is possible by adding out and in modifier to delegate respectively.

Covariance and contravariance limitations

1. Covariance and contravariance only supported for generic Interface and generic delegate types. Generic class doesn’t support covariance. Let’s have a look on below code.

public class A { }
public class B : A{ }
public class D<T>
{
}
D<B> db = new D<B>();
D<A> da = db; //compile time error

As per above code, when D<B> type assigned to D<A> it will throw compile time error (Can’t convert type B to type A).

2. Covariance and contravariance only supports if type is reference type. Value types are not supported by covariance let’s have a look on below code snippet.

int i = 10;
double x = i; //implicitly converts int to double

IEnumerable<double> realnumbers = new List<int>(); // compile time error

As per above code, integer can implicitly convert to double but last line will throws compile time error because covariance doesn’t support value types.




See also -