Sunday, 5 January 2014

Troubleshooting Applications with IIS Logs

Have you ever tried to troubleshoot or debug an application without having ever seen the code? Have you ever had a malfunctioning application, and neither the browser nor the application provided a useful error code?
I’ve encountered both scenarios many times, and it’s a good idea to be prepared for their eventuality. The techniques I’ll describe in this article will help you troubleshoot any application or system running under IIS, no matter what platform it’s coded on. These techniques have helped me troubleshoot applications and Web sites in a variety of situations, especially on devices other than PCs—a scenario that is becoming the norm these days. In a recent case, these techniques helped me discover why videos wouldn’t display on Apple devices though they ran perfectly on Windows-based devices.

Some Considerations

There are many valid techniques for debugging ASP.NET and other Web applications running under IIS. The browser itself often produces a specific error or set of errors that is enough to resolve the issues.
But suppose that information isn’t enough? This is where it becomes handy to know a few extra techniques. The simplest of these is also one of the quickest and best-known—running the application directly on the server. Sometimes the servers aren’t configured for this option, but if you can do it, the server will generally provide more useful debug information than an outside machine. This behavior is obviously built-in by Microsoft for security purposes. To get even more data on a server’s browser, turn off the “Show friendly HTTP error messages” option, which you’ll find in Internet Explorer, under Internet Options | Advanced.
Sometimes you’ll need more information, and that’s when logging becomes essential. Microsoft has built powerful logging facilities into its servers, which will help immensely on any troubleshooting quest, assuming you know what to look for, and where.

Turning on IIS Logging

The first step is to turn on Windows logging on the server. There are several ways to do this. The actual steps can vary (sometimes greatly) depending on which version of Windows Server is running.
Delving into those steps or describing the drawbacks and advantages of each is beyond the scope of this article. Here, I’ll simply point out that to properly use logging to debug your applications, you must turn it on before the actual errors occur. You’ll find a lot of useful information in these two MSDN articles for Windows Server 2003 and 2012: “How to configure Web site logging in Windows Server 2003” (bit.ly/cbS3xZ) and “Configure Logging in IIS” (bit.ly/18vvSgT). If these don’t meet your needs, there are plenty of other online articles relevant to turning on logging in IIS for other versions of Windows Server.

Determine the Proper ID Number

Once logging is on, you need to find out the ID number in IIS of the Web site you’re troubleshooting. This is crucial, as servers typically host more than one Web site, and trying to find the log folder manually can be daunting. (I attempted it on a server running 45 Web sites and it was almost impossible.)
Open IIS Manager to display all Web sites being hosted. For this example, suppose I’m attempting to find out why WebSite2 suddenly stopped working or is only working intermittently.
As you can see in Figure 1, the ID for WebSite2 is “3.” The next step is to open the corresponding log folder, which is typically (but not always) found in the Inetpub folder. Windows usually creates this folder in the root (C:) of the server, but in my case, the Inetpub folder is on the D: drive. Industry best practices advise keeping code and OS drives separate for easy swapping in case of failure.
Finding the Web Site ID Number
Figure 1 Finding the Web Site ID Number

Windows names all logging folders W3SVC#, where # is the ID of the given Web site. Because the ID of the site being debugged in this case is 3, the log files are located in a folder named W3SVC3, as shown in Figure 2.
Opening the Log-File Folder
Figure 2 Opening the Log-File Folder

Browse the Files

When you open the correct folder, you may see a lot of files. IIS usually keeps many different files, depending on how you’ve configured the server history or how long logging has been on. To find the file you need, an almost-sure bet is to scroll to the bottom of the list and open the last file, though if you have the exact time the error occurred, you can locate the file using the date and time in the name of the file. Either way, open the file using a file editor such as Notepad.exe.
You’ll probably see a lot of data in the file. At first glance, the information might seem cryptic and useless, but with a little study you can find plenty of gems buried within this data. I’ll look at some of the most useful data elements recorded by the logging process.
IIS and Windows log an individual line for each HTTP request. A typical line looks like this:
2013-08-28 00:01:12 128.128.128.20 GET /default.asp - 443 - 200.200.200.17 Mozilla/4.0+(compatible; +MSIE+8.0; +Windows+NT+6.1; +WOW64;+Trident/4.0;+SLCC2;+.NET+CLR+2.0.50727; +.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729;+InfoPath.3;+MS-RTC+LM+8; +.NET4.0C;+.NET4.0E; +.NET+CLR+1.1.4322) 200 0 0 15
This is a line from an actual IIS log. The data shown here is in one of the “standard” formats. However, because this option is highly configurable, there’s no guarantee your files will look exactly like my sample. Instead of wading through all the data, I’m going to focus here on the elements that are of most interest to debugging an application.
The first bolded element in the sample is the date of the request. Keep in mind this is the server date. As many Web applications run worldwide across many servers deployed in different time zones, this date can be misleading. Make sure the date accurately reflects the actual time the errors occurred. Many servers use GMT time, but you should validate the format.
Next, you’ll see the IP address that was accessed, the HTTP operation type (GET) and the actual file requested or accessed. In the following sample line, the code is calling the default.asp file:
128.128.128.20 GET /default.asp
This information is valuable, as there may already be errors occurring at this stage of the process. For example, you might be expecting another file to be executed at this point.
The next part of the line shows the IP address where the request originated, as well as the receiving port:
443 - 200.200.200.17
This information is also important, as sometimes it’s necessary to verify that the request you’re troubleshooting actually came from a known source.
As you can see, the actual port used is also referenced. This seemingly unimportant bit of information is vital when looking for issues. For example, the firewall may not be configured correctly. This data is followed by a lot of information, mostly related to versions:
+MSIE+8.0; +Windows+NT+6.1;+WOW64;+Trident/4.0;+SLCC2; +.NET+CLR+2.0.50727; +.NET+CLR+3.5.30729;+.NET+CLR+3.0.30729; +InfoPath.3;+MS-RTC+LM+8; +.NET4.0C
For example, you can see whether the browser is running 32- or 64-bit, the CLR versions (for those who delve that deeply into the .NET universe), and the actual .NET version installed on the server (in this case, .NET 4 C).

Get to the Bottom of Things 

Up to this point, I’ve shown the relatively obvious parts of the log file entry. Most importantly, you can see which browser is responding to the HTTP request. Sometimes this will suffice, as different browsers may produce different results. Here are some partial strings showing what Firefox and Chrome might look like in the file:
;+rv:17.0)+Gecko/20100101+Firefox/17.0 404 0 2 109
+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/­28.0.1500.95+Safari/537.36 200 0 0 125
It can be difficult to detect which of several HTTP requests is being debugged because they all look similar. This is where changing the browser can come in handy. By adding an entry from a different (and unexpected) browser, such as Safari or Opera, it can be easier to find and consequently troubleshoot the entry in question.
Finally, take a look at the last four items on the line:
200 0 0 15
The last number, 15, is the response time (in milliseconds) of the HTTP request. This is a very useful piece of information. Knowing how long a request took to process can help you decide whether a given code snippet, Web service or process is taking the desired or “normal” amount of time.
It may surprise you to discover relatively simple steps in a process are taking unexpected processing time. In a recent case, an application sometimes logged in and sometimes failed to log in, without producing a trappable browser error—or any error at all. It just failed. After reviewing the response times in the log, the developers discovered this property in the web.config file:
<add name="CacheProfile1" duration="30" />
The value of this parameter, apparently harmlessly set to 30 seconds, was simply too large. Once it was reduced, the application worked as expected.
Now (repeating the line here for clarity) I’ll zero in on one of the most important parameters from the set I’m reviewing. The first item, 200, is the actual HTTP response from IIS:
200 0 0 15

That HTTP response code, 200, means success. Often, you’ll encounter a known error type, such as 404 (not found) or 500 (internal server error) and that may give you enough information to troubleshoot and resolve an issue. For an official list of HTTP status codes, visit bit.ly/17sGpwE.
I’ll now relate one more real-world case—the one that actually prompted me to share this article. I had a Web site that worked and executed perfectly on PCs, but as soon as the users accessed the site on their iPad devices, video streaming simply didn’t work. To make things worse, there was no error code; the video just refused to function.
This is where troubleshooting with the logs proved invaluable. By checking the logs and verifying the HTTP request was being made from Safari (to isolate the request), I discovered the server reported a 404 error. The error message was confusing and the error itself seemed implausible, as the PC version of the site worked perfectly.
Though the logs were reporting the object wasn’t being found, I knew very well the files were in place. This prompted me to review the different ways iOS and Windows handle and store files. As I explored the source code that loaded the video, I discovered that the actual path to the video files had been hard-coded in the source, and that the path didn’t exist in iOS iPad devices. That was the reason for the 404.
It’s important to note here that all the symptoms pointed elsewhere. For example, such a problem is typically resolved by checking for the existence of unsupported media types (or Multipurpose Internet Mail Extensions [MIMEs]) in IIS. However, if the problem were a missing MIME type, the error code would have been an HTTP 415 (unsupported Media type) or a similar error, and the logs didn’t report that. Debugging using the IIS logs proved instrumental in finding the problem. I saved a significant amount of time by seeing the actual error code and investigating it, rather than chasing after what would have initially seemed more likely. Once again, knowing how to read the logs saved the day.

Wrapping Up

Log files can be a powerful tool for debugging and troubleshooting applications, even in “blind” situations, provided you know where to find them and what the data means. Investigating the data in the logs is one of the simplest—yet more sophisticated and complete—methods you’ll find to resolve issues.
It takes a little practice and certainly some discipline, but once you’re comfortable with these techniques, you should be able to debug and resolve most application and IIS issues. I’ve put these techniques to good use, and so can you


Source : http://msdn.microsoft.com/en-us/magazine/dn519926.aspx

Monday, 30 December 2013

Difference Between Razor View Engine and ASPX View Engine

View Engine is responsible for rendering the view into html form to the browser. By default, Asp.net MVC support Web Form(ASPX) and Razor View Engine. There are many third party view engines (like Spark, Nhaml etc.) that are also available for Asp.net MVC. Now, Asp.net MVC is open source and can work with other third party view engines like Spark, Nhaml. In this article, I would like to expose the difference between Razor & Web Form View Engine


Thursday, 26 December 2013

Stack, heap, value types, reference types, boxing, and unboxing

What goes inside when you declare a variable?

When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.
That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated that type of memory. There are two types of memory allocation: stack memory and heap memory. In the coming sections, we will try to understand these two types of memory in more detail.

Stack and heap

In order to understand stack and heap, let’s understand what actually happens in the below code internally.
public void Method1()
{
    // Line 1
    int i=4;

    // Line 2
    int y=2;

    //Line 3
    class1 cls1 = new class1();
}
It’s a three line code, let’s understand line by line how things execute internally.
  • Line 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.
  • Line 2: Now the execution moves to the next step. As the name says stack, it stacks this memory allocation on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other.
  • Memory allocation and de-allocation is done using LIFO (Last In First Out) logic. In other words memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.
  • Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.
One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword, it allocates on "heap".
Exiting the method (the fun): Now finally the execution control starts exiting the method. When it passes the end control, it clears all the memory variables which are assigned on stack. In other words all variables which are related to int data type are de-allocated in ‘LIFO’ fashion from the stack.
The big catch – It did not de-allocate the heap memory. This memory will be later de-allocated by the garbage collector.

Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done?
If you look closely, primitive data types are not complex, they hold single values like ‘int i = 0’. Object data types are complex, they reference other objects or other primitive data types. In other words, they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive ones needs static type memory. If the requirement is of dynamic memory, it’s allocated on the heap or else it goes on a stack.
Image taken from http://michaelbungartz.wordpress.com/

Value types and reference types

Now that we have understood the concept of Stack and Heap, it’s time to understand the concept of value types and reference types. Value types are types which hold both data and memory on the same location. A reference type has a pointer which points to the memory location.
Below is a simple integer data type with name i whose value is assigned to another integer data type with name j. Both these memory values are allocated on the stack.
When we assign the int value to the other int value, it creates a completely different copy. In other words, if you change either of them, the other does not change. These kinds of data types are called as ‘Value types’.

When we create an object and when we assign an object to another object, they both point to the same memory location as shown in the below code snippet. So when we assign obj to obj1, they both point to the same memory location.
In other words if we change one of them, the other object is also affected; this is termed as ‘Reference types’.

So which data types are ref types and which are value types?

In .NET depending on the data type, the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types, and any other .NET primitive data types are assigned on the stack. The figure below explains the same in a more detail manner.

Boxing and unboxing

Wow, you have given so much knowledge, so what’s the use of it in actual programming? One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.
Consider the below code snippet. When we move a value type to reference type, data is moved from the stack to the heap. When we move a reference type to a value type, the data is moved from the heap to the stack.
This movement of data from the heap to stack and vice-versa creates a performance hit.
When the data moves from value types to reference types, it is termed ‘Boxing’ and the reverse is termed ‘UnBoxing’.

If you compile the above code and see the same in ILDASM, you can see in the IL code how ‘boxing’ and ‘unboxing’ looks. The figure below demonstrates the same.

Performance implication of boxing and unboxing

In order to see how the performance is impacted, we ran the below two functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.
The boxing function was executed in 3542 ms while without boxing, the code was executed in 2477 ms. In other words try to avoid boxing and unboxing. In a project where you need boxing and unboxing, use it when it’s absolutely necessary.
With this article, sample code is attached which demonstrates this performance implication.


Source : http://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types

Application pool recycle

Recycling the application pool means recycling the worker process (w3wp.exe) and the memory used for the web application. It is a very good practice to recycle the worker process periodically, which wll keep the application running smooth. There are two types of recycling related with the application pool:
  • Recycling Worker Process - Predefined settings
  • Recycling Worker Process - Based on memory
Recycling Worker Process - Predefined Settings
Worker process recycling is the replacing of the instance of the application in memory. IIS 6.0 can automatically recycle worker processes by restarting the worker processes that are assigned to an application pool and associated with websites. This improves web site performance and keeps web sites up and running smoothly.
Application Pool Creation
Application pool recycling- Worker process
There are three types of settings available for recycling worker processes:
  • In minutes
  • Number of requests
  • At a given time

Recycle Worker Process (In Minutes)

We can set a specific time period after which a worker process will be recycled. IIS will take care of all the current running requests.

Recycle Worker Process (Number of Requests)

We can configure an application with a given number of requests. Once IIS reaches that limit, the worker process will be recycled automatically.

Recycle Worker Process (In Minutes)

If we want to recycle the worker process at any given time, we can do that configuration on IIS. We can also set multiple times for this.
Application Pool Creation
Application pool recycling - Worker process: Time setting
Recycling Worker Process - Based on Memory
Server memory is a big concern for any web application. Sometimes we need to clean up a worker process based on the memory consumed by it. There are two types of settings that we can configure in the application pool to recycle a worker process based on memory consumption. These are:
  • Maximum virtual memory used
  • Maximum used memory
Application Pool Creation
Application pool recycling - Worker process.
At any time, if the worker process consumes the specified memory (at memory recycling settings), it will be recycled automatically.

What Happens During Application Pool Recycling

This is quite an interesting question. Based on the above settings, an application pool can be recycled any time. So what happens to the users who are accessing the site at that time? We do not need to worry about that. This process is transparent from the client. When you recycle an application pool, HTTP.SYS holds onto the client connection in kernel mode while the user mode worker process recycles. After the process recycles, HTTP.SYS transparently routes the new requests to the new worker process

Source : http://www.codeproject.com/Articles/42724/Beginner-s-Guide-Exploring-IIS-6-0-With-ASP-NET#heading0015

Application Pool

Application pool is the heart of a website. An Application Pool can contain multiple web sites. Application pools are used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when a worker process or application is having an issue or recycles, other applications or worker processes are not affected.
Application Pool
Application pool - IIS
Generally we do it in our production environment. The main advantages of using an application pool is the isolation of worker processes to differentiate sites and we can customize the configuration for each application to achieve a certain level of performance. The maximum number of application pools that is supported by IIS is 2000.
In this section, I have discussed about the creation of application pools, application pool settings, and assigning an application pool to a web site.

How to Create an Application Pool?

Application pool creation in IIS 6.0 is a very simple task. There are two different ways by which we can create an application pool. There is a pre-defined application pool available in IIS 6.0, called "DefaultApplicationPool". Below are the two ways to create an application pool:
  • Create New Application Pool
  • Create From Existing Configuration File

Create a New Application Pool

First of all, we need to open the IIS Configuration Manager. Then right click on Application Pool and go to New > Application Pool.
Application Pool Creation
Create new application pool
The below screen will appear, where we need to mention the application pool name.
Application Pool Creation
New application pool name
When we create a new application pool, we can use the default application setting for it. The selection of "Default Settings" means by default the application pool setting will be the same as the IIS default settings. If we want to use the configuration of an existing application pool, we need to select the section option "Use existing application pool as template". Selecting this option will enable the application pool name dropdown.
Application Pool Creation
Application pool template selection
If we select an existing application pool as a template, the newly created application pool should have the same configuration of the template application pool. This reduces the time for application pool configuration.
That is all about creating a new application pool. Now let us have a look at the creation of an application pool from an existing XML configuration file.

Create From Existing Configuration File

We can save the configuration of an application pool into an XML file and create a new application pool from that. This is very useful during the configuration of an application pool in a Web Farm where you have multiple web servers and you need to configure the application pool for each and every server. When you are running your web application on a Load Balancer, you need to uniquely configure your application pool.
So first of all, you need to save the application pool configuration in a server. Check the below image for details.
Application Pool Creation
Application pool template selection
During this operation, we can set the password for the configuration file which will be asked during the import of the application pool on another server. When we click on "Save Configuration to a file", the below screen will appear.
Application Pool Creation
Save configuration as XML file
Where we need to provide the file name and location. If we want, we can set a password to encrypt the XML file. Below is a part of that XML:
Location ="inherited:/LM/W3SVC/AppPools/StateServerAppPool"
AdminACL="49634462f0000000a4000000400b1237aecdc1b1c110e38d00"
AllowKeepAlive="TRUE"
AnonymousUserName="IUSR_LocalSystem"
AnonymousUserPass="496344627000000024d680000000076c20200000000"
AppAllowClientDebug="FALSE"
AppAllowDebugging="FALSE"
AppPoolId="DefaultAppPool"
AppPoolIdentityType="2"
AppPoolQueueLength="1000"
AspAllowOutOfProcComponents="TRUE"
AspAllowSessionState="TRUE"
AspAppServiceFlags="0" 
AspBufferingLimit="4194304"
AspBufferingOn="TRUE"
AspCalcLineNumber="TRUE"
AspCodepage="0"pre>
Now we can create a new application pool for this configuration file. While creating a new application pool, we have to select the "Application Pool ( From File )" option as shown in the below figure.
Application Pool Creation
Application pool creation from a configuration file
When we select this option, a screen will come where we need to enter the file name and the password of that file.
Application Pool Creation
Application pool creation from configuration file
Select the file and click on the "Read File" button. This will show you the imported application pool name. Click "OK" to import the full configuration.
Application Pool Creation
Application pool creation from configuration file
Here we need to mention the new application pool name or we can have another option where we can replace an existing application pool. For moving ahead, we need to provide the password.
Application Pool Creation
Password to import application pool configuration
This is the last step for creating a new application pool from an existing configuration file

Saturday, 21 December 2013

Abstract Class vs Interface

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constrants defined


 I have explained the differences between an abstract class and an interface.

Wednesday, 27 November 2013

Asynchronous Programming in .Net: Async and Await for Beginners

Introduction

There are several ways of doing asynchronous programming in .Net.  Visual Studio 2012 introduces a new approach using the ‘await’ and ‘async’ keywords.  These tell the compiler to construct task continuations in quite an unusual way.
I found them quite difficult to understand using the Microsoft documentation, which annoyingly keeps saying how easy they are.
This series of articles is intended to give a quick recap of some previous approaches to asynchronous programming to give us some context, and then to give a quick and hopefully easy introduction to the new keywords

Example

By far the easiest way to get to grips with the new keywords is by seeing an example.  For this initially I am going to use a very basic example: you click a button on a screen, it runs a long-running method, and displays the results of the method on the screen.
Since this article is about asynchronous programming we will want the long-running method to run asynchronously on a background thread.  This means we need to marshal the results back on to the user interface thread to display them.
In the real world the method could be running a report, or calling a web service.  Here we will just use the method below, which sleeps to simulate the long-running process:
        private string LongRunningMethod(string message)
        {
            Thread.Sleep(2000);
            return "Hello " + message;
        }
The method will be called asynchronously from a button click method, with the results assigned to the content of a label.

Coding the Example with Previous Asynchronous C# Approaches

There are at least five standard ways of coding the example above in .Net currently.  This has got so confusing that Microsoft have started giving the various patterns acronyms, such as the ‘EAP‘ and the ‘APM‘.   I’m not going to talk about those as they are effectively deprecated.  However it’s worth having a quick look at how to do our example using some of the other approaches.

Coding the Example by Starting our Own Thread

This simple example is fairly easy to code by just explicitly starting a new thread and then using Invoke or BeginInvoke to get the results back onto the UI thread.  This should be familiar to you:
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            new Thread(() => { 
                string result = LongRunningMethod("World");
                Dispatcher.BeginInvoke((Action)(() => Label1.Content = result)); 
            }).Start();
            Label1.Content = "Working...";
        }
We start a new thread and hand it the code we want to run.  This calls the long-running method and then uses Dispatcher.BeginInvoke to call back onto the user interface thread with the result and update our label.
Note that immediately after we start the new thread we set the content of our label to ‘Working…’.  This is to show that the button click method continues immediately on the user interface thread after the new thread is started.
The result is that when we click the button our label says ‘Working…’ almost immediately, and then shows ‘Hello World’ when the long-running method returns.  The user interface will remain responsive whilst the long-running thread is running.

Coding the Example Using the Task Parallel Library (TPL)

More instructive is to revisit how we would do this with tasks using the Task Parallel Library.  We would typically use a task continuation as below.
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Task.Run<string>(() => LongRunningMethod("World"))
                .ContinueWith(ant => Label2.Content = ant.Result, 
                              TaskScheduler.FromCurrentSynchronizationContext());
            Label2.Content = "Working...";
        }
Here we’ve started a task on a background thread using Task.Run.  This is a new construct in .Net 4.5.  However, it is nothing more complicated than Task.Factory.StartNew with preset parameters.  The parameters are the ones you usually want to use.  In particular Task.Run uses the default Task Scheduler and so avoids one of the hidden problems with StartNew.
The task calls the long-running method, and does so on a threadpool thread.  When it is done a continuation runs using ContinueWith.  We want this to run on the user interface thread so it can update our label.  So we specify that it should use the task scheduler in the current synchronization context, which is the user interface thread when the task is set up.
Again we update the label after the task call to show that it returns immediately.  If we run this we’ll see a ‘Working…’ message and then ‘Hello World’ when the long-running method returns.

Coding the Example Using Async and Await

Code

Below is the full code for the async/await implementation of the example above.  We will go through this in detail.
       private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            CallLongRunningMethod();
            Label3.Content = "Working...";        
        }

        private async void CallLongRunningMethod()
        {
            string result = await LongRunningMethodAsync("World");
            Label3.Content = result;
        }

        private Task<string> LongRunningMethodAsync(string message)
        {
            return Task.Run<string>(() => LongRunningMethod(message));
        }

        private string LongRunningMethod(string message)
        {
            Thread.Sleep(2000);
            return "Hello " + message;
        }

Asynchronous Methods

The first thing to realize about the async and await keywords is that by themselves they never start a thread.  They are a way of controlling continuations, not a way of starting asynchronous code.
As a result the usual pattern is to create an asynchronous method that can be used with async/await, or to use an asynchronous method that is already in the framework.  For these purposes a number of new asynchronous methods have been added to the framework.
To be useful to async/await the asynchronous method has to return a task.  The asynchronous method has to start the task it returns as well, something that maybe isn’t so obvious.
So in our example we need to make our synchronous long-running method into an asynchronous method.  The method will start a task to run the long-running method and return it.  The usual approach is to wrap the method in a new method.   It is usual to give the method the same name but append ‘Async’.  Below is the code to do this for the method in our example:
        private Task<string> LongRunningMethodAsync(string message)
        {
            return Task.Run<string>(() => LongRunningMethod(message));
        }
Note that we could use this method directly in our example without async/await.  We could call it and use ‘ContinueWith’ on the return value to effect our continuation in exactly the same way as in the Task Parallel Library code above.  This is true of the new async methods in the framework as well.

Async/Await and Method Scope

Async and await are a smart way of controlling continuations through method scope.  They are used as a pair in a method as shown below:
        private async void CallLongRunningMethod()
        {
            string result = await LongRunningMethodAsync("World");
            Label3.Content = result;
        }
Here async is simply used to tell the compiler that this is an asynchronous method that will have an await in it.  It’s the await itself that’s interesting.
The first line in the method calls LongRunningMethodAsync, clearly.  Remember that LongRunningMethodAsync is returning a long-running task that is running on another thread.  LongRunningMethodAsync starts the task and then returns reasonably quickly.
The await keyword ensures that the remainder of the method does not execute until the long-running task is complete.  It sets up a continuation for the remainder of the method. Once the long-running method is complete the label content will update: note that this happens on the same thread that CallLongRunningMethod is already running on, in this case the user interface thread.
However, the await keyword does not block the thread completely.  Instead control is returned to the calling method on the same thread.  That is, the method that called CallLongRunningMethod will execute at the point after the call was made.
The code that calls LongRunningMethod is below:
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            CallLongRunningMethod();
            Label3.Content = "Working...";        
        }
So the end result of this is exactly the same as before.  When the button is clicked the label has content ‘Working…’ almost immediately, and then shows ‘Hello World’ when the long-running task completes.

Return Type

One other thing to note is that LongRunningMethodAsync returns a Task<string>, that is, a Task that returns a string.  However the line below assigns the result of the task to the string variable called ‘result’, not the task itself.
string result = await LongRunningMethodAsync("World");
The await keyword ‘unwraps’ the task.  We could have attempted to access the Result property of the task (string result = LongRunningMethodAsync(“World”).Result.  This would have worked but would have simply blocked the user interface thread until the method completed, which is not what we’re trying to do.
I’ll discuss this further below.

Recap

To recap, the button click calls CallLongRunningMethod, which in turn calls LongRunningMethodAsync, which sets up and runs our long-running task.  When the task is set up (not when it’s completed) control returns to CallLongRunningMethod, where the await keyword passes control back to the button click method.
So almost immediately the label content will be set to “Working…”, and the button click method will exit, leaving the user interface responsive.
When the task is complete the remainder of CallLongRunningMethod executes as a continuation on the user interface thread, and sets the label to “Hello World”.

Async and Await are a Pair

Async and await are always a pair: you can’t use await in a method unless the method is marked async, and if you mark a method async without await in it then you get a compiler warning.  You can of course have multiple awaits in one method as long as it is marked async.

Aside: Using Anonymous Methods with Async/Await

If you compare the code for the Task Parallel Library (TPL) example with the async/await example you’ll see that we’ve had to introduce two new methods for async/await: for this simple example the TPL code is shorter and arguably easier to understand.  However, it is possible to shorten the async/await code using anonymous methods, as below. This shows how we can use anonymous method syntax with async/await, although I think this code is borderline incomprehensible:
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            new Action(async () =>
            {
                string result = await Task.Run<string>(() => LongRunningMethod("World"));
                Label4.Content = result;
            }).Invoke();
            Label4.Content = "Working...";
        }

Using the Call Stack to Control Continuations

Overview of Return Values from Methods Marked as Async

There’s one other fundamental aspect of async/await that we have not yet looked at.  In the example above our method marked with the async keyword did not return anything.  However, we can make all our async methods return values wrapped in a task, which means they in turn can be awaited on further up the call stack.  In general this is considered good practice: it means we can control the flow of our continuations more easily.
The compiler makes it easy for us to return a value wrapped in a task from an async method.  In a method marked async the ‘return’ statement works differently from usual.  The compiler doesn’t simply return the value passed with the statement, but instead wraps it in a task and returns that instead.

Example of Return Values from Methods Marked as Async

Again this is easiest to see with our example.  Our method marked as async was CallLongRunningMethod, and this can be altered to return the string result to the calling method as below:
        private async Task<string> CallLongRunningMethodReturn()
        {
            string result = await LongRunningMethodAsync("World");
            return result;
        }
We are returning a string (‘return result’), but the method signature shows the return type as Task<string>.  Personally I think this is a little confusing, but as discussed it means the calling method can await on this method.  Now we can change the calling method as below:
        private async void Button_Click_5(object sender, RoutedEventArgs e)
        {
            Label5.Content = "Working...";
            string result = await CallLongRunningMethodReturn();
            Label5.Content = result;
        }
We can await the method lower down the call stack because it now returns a task we can await on.  What this means in practice is that the code sets up the task and sets it running and then we can await the results from the task when it is complete anywhere in the call stack.  This gives us a lot of flexibility as methods at various points in the stack can carry on executing until they need the results of the call.
As discussed above when we await on a method returning type Task<string> we can just assign the result to a string as shown.  This is clearly related to the ability to just return a string from the method: these are syntactic conveniences to avoid the programmer having to deal directly with the tasks in async/await.
Note that we have to mark our method as ‘async’ in the method signature (‘private async void Button_Click_5′) because it now has an await in it, and they always go together.

What the Code Does

The code above has exactly the same result as the other examples: the label shows ‘Working…’ until the long-running method returns when it shows ‘Hello World’.  When the button is clicked it sets up the task to run the long-running method and then awaits its completion both in CallLongRunningMethodReturn and Button_Click_5.  There is one slight difference in that the click event is awaiting: previously it exited.  However, if you run the examples you’ll see that the user interface remains responsive whilst the task is running.

What’s The Point?

If you’ve followed all the examples so far you may be wondering what the point is of the new keywords.  For this simple example the Task Parallel Library syntax is shorter, cleaner and probably easier to understand than the async/await syntax.  At first sight async/await are a little confusing.
The answer is that for basic examples async/await don’t seem to me to be adding a lot of value, but as soon as you try to do more complex continuations they come into their own.  For example it’s possible to set up multiple tasks in a loop and write very simple code to deal with what happens when they complete, something that is tricky with tasks.  I suggest you look at the examples in the Microsoft documentation which do show the power of the new keywords

Source : http://richnewman.wordpress.com/2012/12/03/tutorial-asynchronous-programming-async-and-await-for-beginners/