Monday, February 14, 2011

Application Domain and its configuration (Part-1)

In .net all application assembly run under an application domain that is created by default for each application, we don’t need to create it. Common Language Runtime does it for application.

Developers often need to run an external assembly. However, running an external
assembly can lead to inefficient resource usage and security vulnerabilities. The best way to manage these risks is to create an application domain and call the assembly from within the protected environment.

Application domain is logical unit to run different application in a single process. IIS is the very good example of it, in IIS more than one website or application are hosted, still they run independent with out interfering to any other application, hosted on same IIS.

Application domain creates a separate layer for application; .net run time is responsible for the various application runtime, while operating system manage process. In a process, we can run more than one application domain and each application domain has one or more assembly, application running. Each of these application domains can’t access resource or memory used by another application domain.

To create an application domain is as simple as we create an object of a class. The benefit of application domain is that when we don’t require or our work has been completed we can unload resource occupied by application runtime.

System.AppDomain class provides many methods and property to manipulate application domain.

1. Create an application domain

AppDomain ad = new AppDomain(“myAppDomain”);

We can run our assembly under this newly created Application domain.

ad.ExecuteAssembly(“myAssembly.exe”);

We can either call ExecuteAssemblyByName method to run assembly, in that case we need to pass name of assembly.

ad.ExecuteAssembly(“myAssembly.exe”);

There are so many properties and methods provide by AppDomain which gives ability to specify ID to process, friendlyname etc. Methods like Load, ApplyPolicy,CreateIntance etc.

If you notice in above code, we don’t have any constructor to create application domain, we are using static method of AppDomain class.

We can access current domains by ..

AppDomain myCurrentDomain = AppDomain.CurrentDomain;

To unload application domain, call Unload method of AppDomain

AppDomain.Unload(ad);

Threading Part - 2


This post is in continuation with Threading Part - 1....

In first post, we have seen the basic understanding on the Threading and its usage.
Now, let us consider comparatively complex scenarios....

Using Thread.Join
More often than not, you will need your application to wait for a thread to complete
execution. To accomplish this, the Thread class supports the Join method:

// C#
theThread.Join();

The Join method tells the system to make your application wait until the thread has
completed. Of course, in this simple case you do not really need a second thread
because you are just waiting for it to complete anyway. A better example is for us to
have five threads that all do some work and to wait for them. When we are working
with multiple threads, our programming task is a bit more complicated, as we need to
wait for all our threads. We can do this by keeping a reference to all our threads and calling Join on each of the threads to wait for the threads to complete, one at a time,as demonstrated in the following code:

// C#
ThreadStart operation = new ThreadStart(SomeWork);
Thread[] theThreads = new Thread[5];
for (i nt x = 0; x < 5; ++x)
{
// Creates, but does not start, a new thread
theThreads[x] = new Thread(operation);
// Starts the work on a new thread
theThreads[x].Start() ;
}
// Wai t for each thread to complete
foreach (Thread t in theThreads)
{
t.Join();
}
By storing the threads in an array, we can wait for each of the Threads one at a time. As each thread completes, the Join method will return and we can continue.

Thread Priority
The Thread class supports the setting or getting of the priority of a thread using the ThreadPriority enumeration.

  1. Highest - The highest priority
  2. AboveNormal - Higher priority than Normal
  3. Normal - The default priority
  4. BelowNormal - Lower than Normal
  5. Lowest - The lowest priority



Threads are scheduled based on this enumeration. In most cases, you will want to use
the default (Normal). Deciding to use threads that have lower thread priority can
cause the operation system to starve a thread more than you might expect, or if you
use higher priorities (especially Highest), you can starve the system. Although it is necessary to use non-Normal thread priorities at times, make this decision with much caution. Increasing the performance of a system simply by increasing thread priority is not likely to help in the long term, as other starved threads tend to back up and cause unexpected consequences.

Passing Data to Threads
In each of the earlier examples, we were using the ThreadStart delegate, which takes
no parameters. In most real-world use of threading, you will need to pass information
to individual threads. To do this, you need to use a new delegate called ParameterizedThreadStart. This delegate specifies a method signature with a single parameter of type Object and returns nothing. The following code snippet provides an example:

// C#
static void WorkWithParameter(object o)
{
string i nfo = (string) o;
for (int x = 0; x < 10; ++x)
{
Console. WriteLine("{0}: {1}", i nfo,
Thread.CurrentThread.ManagedThreadId);
// Slow down thread and let other threads work
Thread. Sleep(10);
}
}

This is a method that takes a single Object parameter (and therefore can be a reference to any object). To use this as the starting point of a thread call, you can create a ParameterizedThreadStart delegate to point at this new method and use the Thread.Start method’s overload that takes a single object parameter. The following code snippet provides an example:

// C#
ParameterizedThreadStart operation = new ParameterizedThreadStart(WorkWithParameter);
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start("Hel l o");
// A Second Thread wi th a different parameter
Thread newThread = new Thread(operation);
newThread.Start("Goodbye");

Be aware that because the WorkWithParameter method takes an object, Thread. Start
could be called with any object instead of the string it expects. Being careful in choosing your starting method for a thread to deal with unknown types is crucial to good threading code. Instead of blindly casting the method parameter into our string, it is a better practice to test the type of the object, as shown in the following example:
// C#
string i nfo = o as string;
if (info == null )
{
throw Invali dProgramException("Parameter for thread must be a string");
}

Threading Part - 1


Most of the time developer chooses to develop program in linear way. In this mechanism user would need to wait sometime in some situation like application is going to download page from server, application is going to print document, applications is going to access remote database. Those cases are time consuming, user needs to wait till main thread completes work, sometime user get frustrated by response time, and application does not response to user till task has been completed.
To overcome, .net has provided threading mechanism. Our main thread executes as and in background we can execute process. So user will not feel that application is not responding, in background thread method executes and once result will be available, it would be shown to user.

Threading means in a single process execute more than one task among different processors. Now days most of computers are more than one core, we can use another core when main core is busy to complete task. We can distribute work task among different processors.

Though multithreading seems to be very complex, .net has provided a simple way to implement in programming. At a time there can be more than 250 threads run in back ground. We can even change it to more if required.

To work with thread we need to add System.Threading namespace to our application.

Creating a Thread
To create and start a new thread, follow these steps:
1. Create a method that takes no arguments and does not return any data (for example, use the void return type for C#). This method should look something like this:

// C#
static void SimpleWork()
{
Console. WriteLine("Thread: {0}", Thread. CurrentThread. ManagedThreadId);
}
2. Create a new ThreadStart delegate, and specify the method created in step 1.
3. Create a new Thread object, specifying the ThreadStart obj ect created in step 2.
4. Call Thread.Start to begin execution of the new thread.
Your code will end up looking something like this:

// C#
ThreadStart operation = new ThreadStart(SimpleWork);
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start();

When the Start method is called, the SomeWork method is called on a new thread and
the thread executes until the method completes. In this example, our SimpleWork
method writes the phrase “In Thread” and shows the ManagedThreadId property. This
property is a numeric number assigned to every thread.

Using Multiple Threads
A more likely scenario than this simple case is one in which you’ll want to create
multiple threads to do work. For example, we can change the example just shown to
create multiple threads and start them all on the same work:
// C#
ThreadStart operation = new ThreadStart(SimpleWork);
for (i nt x = 1; x <= 5; ++x)
{
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start();
}

This executes the work on five separate threads, as concurrently as your particular
machine is capable of doing. If we implement this change, we should get five separate
threads all writing out their own thread ID to the console window:
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7

We see consecutive thread numbers because the work we are doing in SimpleWork is
very quick. Let’s change our work to something a little more lengthy so that we can
see the threads working concurrently:

// C#
static void Simpl eWork()
{
for (int x = 1; x <= 10; ++x)
{
Console. WriteLine("Thread: {0}",
Thread.CurrentThread.ManagedThreadId);
// Sl ow down thread and let other threads work
Thread.Sl eep(10);
}
}

In this new version of SimpleWork, we are writing out our thread identifier 10 times.
In addition, we are using Thread.Sleep to slow down our execution. The Thread.Sleep
method allows us to specify a time in milliseconds to let other threads perform work.
On every thread, we are allowing 10 milliseconds for the other threads to write their
own data to the console. To see how this works, we can change our SimpleWork method to write out the iteration it is working on:

Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7

Doing this allows us to perform operations as concurrently as our hardware will
allow. As our work increases and the time it takes to complete each thread becomes longer, we will need to determine how to make our main thread (the one that the thread creation code exists on) wait until all the work is complete. This is where the Thread.Join method comes in.


Thread which runs first is called Forground and other called background.

static void ThreadProc(object msg)
{
string threadMsg = (string)msg;
if (Thread.CurrentThread.IsBackground)
{
Console.WriteLine(“Background Thread”);
Console.WriteLine(“My Threading method with:” + threadMsg);
}
else
{
Console.WriteLine(“Forground Thread”);
Console.WriteLine(“My Threading method with:” + threadMsg);
}
}
We can check weather thread is background or not with Thread.CurrentThread.IsBackGround property.
Some time threading also overheads on processors, so need to take care while implementing threading as it distribute loads to different processor, more memory is required to manage resource.
Wise use of threading may improve application’s performance. It depends on requirement and application problem to use of Threading.