What mechanism do async tasks use in ASP.Net MVC 4.0? - asynchronous

What is the mechanism behind async tasks in MVC 4? How is it related to normal threading? Please provide detail.

If you are interested in async and await keywords, you might find this Channel 9 interview with Anders Hejlsberg interesting.
Also, take a look at: this PDC video.

As already indicated before, async keyword is part of .Net. For better implementation of asynchronous programming, Microsoft has released several CTPs for this and it will be out of the box on .Net 4.5 AFAIK.
Below article is helpful as well :
http://www.juliencorioland.net/Archives/en-aspnet-mvc-4-asynchronous-controllers

Normally, a single ASP.NET page request is handled by a single thread. After the thread sends the response, it returns to the ASP.NET thread pool.
When you use async/await (or asynchronous pages), the thread handling the request marks the request as incomplete and then returns to the ASP.NET thread pool. When the awaitable completes later, an ASP.NET thread is assigned to run the rest of the method.
More specifically, async/await by default use SynchronizationContext. See my MSDN article for more details.

Async Tasks is a feature of .NET, not of ASP.NET MVC 4. They work the same in ASP.NET as they do elsewhere within .NET.

Related

How were WebAPI requests cancelled in the olden days before async/await?

In .NET 4.5, using the async/await pattern, a web request can be easily cancelled by including a CancellationToken in an async controller method. This of course can be passed to any async Entity Framework methods, and the whole thing can be cancelled nicely.
But going back 6 years, before the days of async, how were WebAPI or MVC controller methods cancelled? Was it even possible? And if so, was it possible to also cancel long-running Entity Framework queries within those cancelled requests?
My motivation for asking is that I've run some experiments and found that in almost all cases, my synchronous versions of large-ish EF queries are faster than their async counterparts. The async versions vary between 10 and 50% longer. Furthermore, my application is for internal use and will realistically only ever serve a maximum of 3 concurrent users, so scalability is a non-issue.
In short, I want the speed of the old-fashioned, synchronous Entity Framework methods (and therefore, synchronous controller methods), but with cancellability.
But going back 6 years, before the days of async, how were WebAPI or MVC controller methods cancelled? Was it even possible? And if so, was it possible to also cancel long-running Entity Framework queries within those cancelled requests?
Legacy ASP.NET uses Thread.Abort to cancel synchronous requests. This of course eventually causes application instability, so ASP.NET will regularly recycle your app domain (and service process).
I'm not sure if legacy ASP.NET uses Thread.Abort to cancel asynchronous requests (while they are running code, I mean). I would assume so, but I don't know for sure.
As a final note, please do notify the EF team of your performance issues.

When to use TaskFactory in Asp.Net Web applications (webform or mvc)?

I am working in WPF now...here we use Background_Worker,TaskFactory.StartNew functions and async/await.
In web apps I know that we have AJAX, MVC partial views etc.
My question is do we really use above mentioned async methods (Tasks, sync/await) in Web apps ? If we use, could you give me some examples ?
I have a document generation module in my web app in which I have to fetch data from DB and create documents out of it. Is it a good scenario for async calls? (to call the function and throw..and never care about it).
I am working in WPF now...here we use Background_Worker,TaskFactory.StartNew functions and async/await.
You really should be using Task.Run instead of BackgroundWorker and Task.Factory.StartNew. Task.Run has much better defaults than StartNew, and is more composable and type-safe than BackgroundWorker.
My question is do we really use above mentioned async methods (Tasks, sync/await) in Web apps ?
On ASP.NET, you should almost never use your own background threads (BackgroundWorker, StartNew, Task.Run). However, you certainly can use async and await.
If we use, could you give me some examples ? I have a document generation module in my web app in which I have to fetch data from DB and create documents out of it.
Yes, database queries are one example of an I/O-based operation. So is "writing" documents - whether as uploads to cloud storage or to the local file system.
I have an MSDN article on async ASP.NET that you may find useful.
Async is useful any time you have disk/database/network I/O. It allows you to do other things while you wait for the I/O to complete, which can result in significant savings. Async isn't really useful for normal CPU bound operations, because of the increased overhead of making it async.
This holds true in WPF as well web applications.
If you want to see a concrete example, Scott Hanselman has a blog entry entitled The Magic of using Asynchronous Methods in ASP.NET 4.5 plus an important gotcha which you may find very interesting.

Are WCF request handling Thread Agile?

I have seen lots of documentation on how Agile Asp.Net Request handling is? I want to know is the case same with WCF Request handling. Can we rely on the fact that the Thread that starts Wcf request handling will finish it?
I am maintaining a Wcf Application where at lots of places ThreadStatic variables are used. Although the code is working but is it reliable? Is it worth changing it or should I keep it as it is?
When creating a WCF service you can set the threading and service instantiating behaviour, by decorating the service implementation class with a ServiceBehavior attribute:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
class SingleCachingHttpFetcher : IHttpFetcher
The above code snippet is from http://msdn.microsoft.com/en-us/library/system.servicemodel.servicebehaviorattribute.concurrencymode.aspx
EDIT
I dit a bit more research and found this article: http://blogs.microsoft.co.il/blogs/applisec/archive/2009/11/23/wcf-thread-affinity-and-synchronization.aspx. It basically says that no, you cannot be sure that the same thread starting the request will be the one finishing it.
EDIT 2
This question has been discussed before at StackOverflow. It links to How to make a WCF service STA (single-threaded) where there is a description on how to create an OperationBehavior which will force a single threaded apartment. The example deals with calling GUI components, but it should work for other single threaded requirements as well.

How To Implement ReverseAJAX (Comet) in ASP.Net MVC

How could I implement a Comet architecture in a ASP.Net MVC?
The paid alternative
There are great comments about the question in this thread.
And based in the fact you can use handlers in a MVC app:
WebSync
will do the work : )
As long as you need to implement server push support onto your ASP.NET MVC application you will need some extra functionalities like detection of client status etc. I suggest you to try PokeIn comet ajax library which you can find sample project here
I doubt you will find something out of the box for MVC but you can always implement the client side code that handles timeouts and reconnects to an AJAX-enabled WCF service that polls for whatever event you want to be notified for. Be sure to set the timeout of the service to a higher value.
Edit 24.11.2013
Since the original question was posted SignalR was released which is a library to do just that.

Asynchronous web service call in ASP.NET/C#

We have an application that hits a web service successfully, and the data returned updates our DB. What I'm trying to do is allow the user to continue using other parts of our web app while the web service processes their request and returns the necessary data.
Is this asynchronous processing? I've seen some console app samples on the msdn site, but considering this is a web form using a browser I'm not sure those samples apply. What if the user closes the browser window mid request? Currently we're using the Message Queue which "waits" for the web service to respond then handles the DB update, but we'd really like to get rid of that.
I'm (obviously) new to async requests and could use some help figuring this out. Does anyone have some code samples or pertinent articles I could check out?
Yes, what you're describing is async processing.
The best solution depends to some degree on the nature of the web services call and how you want to handle the results. A few tips that might help:
One approach is to send a request from the initial web request to a background thread. This works best if your users don't need to see the results of the call as soon as it completes.
Another approach is to have your server-side code make an async web services call. This is the way to go if your users do need to see the results. The advantage of an async call on the server side is that it doesn't tie up an ASP.NET worker thread waiting for results (which can seriously impair scalability)
Your server-side code can be structured either as a web page (*.aspx) or a WCF service, depending on what you want to have it return. Both forms support async.
From the client, you can use an async XMLHTTP request (Ajax). That way, you will receive a notification event when the call completes.
Another approach for long-running tasks is to write them to a persistent queue using Service Broker. This works best for things that you'd like users to be able to start and then walk away from and see the results later, with an assurance that the task will be completed.
In case it helps, I cover each of these techniques in detail in my book, along with code examples: Ultra-Fast ASP.NET.
If you're not blocking for a method return you're doing asychronous processing. Have a look at Dino Esposito's article on using AJAX for server task checking.
You can perform asynchronous web service calls using both Web Service Enhancements (WSE) and Windows Communication Foundation (WCF) in your C# code. WSE is discontinued, so its use is not recommended. Generically speaking, if you were to terminate program execution in the middle of an asynchronous call before the response returned, nothing bad would happen; the client would simply not process the result, but the web service would still be able to perform its processing to completion.
If your client web application is responsible for updating the DB, then without anything else in your client code, quitting in the middle of an asynchronous operation would mean that the DB was not updated. However, you could add some code to your client application that prevented the browser from quitting entirely while it is waiting for an asynchronous response while preventing new web service calls from being run after Close is called (using Javascript).
You have 2 distinct communications here: (1) from web browser to web application and (2) from web application to web service.
diagram http://img697.imageshack.us/img697/6713/diagramo.png
There is no point of making (2) asynchronous: you still would have to wait for web service to finish processing request. If you end HTTP request from browser to web application the client would have no clue what the result of request was.
It is much better to make asynchronous request from web browser to your web application. Ajax is ideal for that. In fact, that's what it was created for. Here's couple of links to get you started:
jQuery Ajax
ASP.NET AJAX

Resources