Tuesday, April 30, 2013

ASP.NET Core Runtime and Framework


Asynchronously Reading and Writing HTTP Requests and Responses

ASP.NET 4 introduced the ability to read an HTTP request entity as a stream using theHttpRequest.GetBufferlessInputStream method. This method provided streaming access to the request entity. However, it executed synchronously, which tied up a thread for the duration of a request.
ASP.NET 4.5 supports the ability to read streams asynchronously on an HTTP request entity, and the ability to flush asynchronously. ASP.NET 4.5 also gives you the ability to double-buffer an HTTP request entity, which provides easier integration with downstream HTTP handlers such as .aspx page handlers and ASP.NET MVC controllers.

Improvements to HttpRequest handling

The Stream reference returned by ASP.NET 4.5 from HttpRequest.GetBufferlessInputStream supports both synchronous and asynchronous read methods. The Stream object returned from GetBufferlessInputStream now implements both the BeginRead and EndRead methods. The asynchronous Stream methods let you asynchronously read the request entity in chunks, while ASP.NET releases the current thread between each iteration of an asynchronous read loop.
ASP.NET 4.5 has also added a companion method for reading the request entity in a buffered way:HttpRequest.GetBufferedInputStream. This new overload works like GetBufferlessInputStream, supporting both synchronous and asynchronous reads. However, as it reads, GetBufferedInputStream also copies the entity bytes into ASP.NET internal buffers so that downstream modules and handlers can still access the request entity. For example, if some upstream code in the pipeline has already read the request entity using GetBufferedInputStream, you can still use HttpRequest.Form or HttpRequest.Files. This lets you perform asynchronous processing on a request (for example, streaming a large file upload to a database), but still run .aspx pages and MVC ASP.NET controllers afterward.

Asynchronously flushing a response

Sending responses to an HTTP client can take considerable time when the client is far away or has a low-bandwidth connection. Normally ASP.NET buffers the response bytes as they are created by an application. ASP.NET then performs a single send operation of the accrued buffers at the very end of request processing.
If the buffered response is large (for example, streaming a large file to a client), you must periodically callHttpResponse.Flush to send buffered output to the client and keep memory usage under control. However, becauseFlush is a synchronous call, iteratively calling Flush still consumes a thread for the duration of potentially long-running requests.
ASP.NET 4.5 adds support for performing flushes asynchronously using the BeginFlush and EndFlush methods of theHttpResponse class. Using these methods, you can create asynchronous modules and asynchronous handlers that incrementally send data to a client without tying up operating-system threads. In between BeginFlush and EndFlushcalls, ASP.NET releases the current thread. This substantially reduces the total number of active threads that are needed in order to support long-running HTTP downloads.

Support for await and Task-Based Asynchronous Modules and Handlers

The .NET Framework 4 introduced an asynchronous programming concept referred to as a task. Tasks are represented by the Task type and related types in the System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this with compiler enhancements that make working with Task objects simple. In the .NET Framework 4.5, the compilers support two new keywords: await and async. The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods.
The combination of awaitasync, and the Task object makes it much easier for you to write asynchronous code in .NET 4.5. ASP.NET 4.5 supports these simplifications with new APIs that let you write asynchronous HTTP modules and asynchronous HTTP handlers using the new compiler enhancements.

Asynchronous HTTP modules

Suppose that you want to perform asynchronous work within a method that returns a Task object. The following code example defines an asynchronous method that makes an asynchronous call to download the Microsoft home page. Notice the use of the async keyword in the method signature and the await call to DownloadStringTaskAsync.
private async Task
ScrapeHtmlPage(object caller, EventArgs e)
 {
 WebClient wc = new WebClient();
 var result = await wc.DownloadStringTaskAsync("http://www.microsoft.com");
 // Do something with the result
}
That's all you have to write — the .NET Framework will automatically handle unwinding the call stack while waiting for the download to complete, as well as automatically restoring the call stack after the download is done.
Now suppose that you want to use this asynchronous method in an asynchronous ASP.NET HTTP module. ASP.NET 4.5 includes a helper method (EventHandlerTaskAsyncHelper) and a new delegate type (TaskEventHandler) that you can use to integrate task-based asynchronous methods with the older asynchronous programming model exposed by the ASP.NET HTTP pipeline. This example shows how:
public void Init(HttpApplication
context)
 {
   // Wrap the Task-based method so that it can be used with 
   // the older async programming model.
   EventHandlerTaskAsyncHelper helper = 
     new EventHandlerTaskAsyncHelper(ScrapeHtmlPage);
 
     // The helper object makes it easy to extract Begin/End methods out of
     // a method that returns a Task object. The ASP.NET pipeline calls the 
     // Begin and End methods to start and complete calls on asynchronous 
     // HTTP modules.
     context.AddOnPostAuthorizeRequestAsync(
      helper.BeginEventHandler, helper.EndEventHandler);
 }

Asynchronous HTTP handlers

The traditional approach to writing asynchronous handlers in ASP.NET is to implement the IHttpAsyncHandlerinterface. ASP.NET 4.5 introduces the HttpTaskAsyncHandler asynchronous base type that you can derive from, which makes it much easier to write asynchronous handlers.
The HttpTaskAsyncHandler type is abstract and requires you to override the ProcessRequestAsync method. Internally ASP.NET takes care of integrating the return signature (a Task object) of ProcessRequestAsync with the older asynchronous programming model used by the ASP.NET pipeline.
The following example shows how you can use Task and await as part of the implementation of an asynchronous HTTP handler:
public class MyAsyncHandler : HttpTaskAsyncHandler
{
 // ...
 
 // ASP.NET automatically takes care of integrating the Task based override
 // with the ASP.NET pipeline.
 public override async Task ProcessRequestAsync(HttpContext context)
 {
     WebClient wc = new WebClient();
     var result = await 
      wc.DownloadStringTaskAsync("http://www.microsoft.com");
     // Do something with the result
 }
}
What's New in ASP.NET 4.5 and Visual Studio 2012

This Post describes new features and enhancements that are being introduced in ASP.NET 4.5. It also describes improvements being made for web development in Visual Studio (Visual Web Developer).