Friday, April 3, 2015

ASP.NET Async Tips


  • Avoid using background threads in ASP.NET as there are no background threads on servers unlike a WPF or Console application. For the latter, it may be a good idea to keep the async work separate from the main UI thread to avoid locking up the UI. But there is no separate UI thread for Web Applications to lock up! 

  • Doing so gives up the current thread for processing other requests, but you end up taking another thread from the same thread pool, only adding up the cost for a thread swap for no reason. All threads come from the same pool used to serve requests. Moving to another thread just adds cost.

  • If indeed you need a real background thread legitimate reason, consider using SynchronizationContext.Post which can be used in a thread safe manner.

  • Avoid using Task.Wait in ASP.NET like the plague. It is blocking and often causes deadlocks. Deadlocks occur because the framework spins up locks to make thread run thread-safe. But in ASP.NET if blocking using Task.Wait on the same thread it is very easy to cause a deadlock with async code.

  • Avoid Task.ContinueWith as it is not aware of SynchronizationContext and always puts you on a new thread! This has become redundant with await and await is aware of SynchronizationContext is the task does end up running in a separate thread.

  • Be careful with parallelism on the ASP.NET server. Multiple requests * multiple threads can quickly lead to thread starvation for as all threads come from the same pool. Threads consume minimum of 1/4 MB each.

  • However kicking off multiple awaitable async tasks is fine. This actually helps scale your application better as the same thread can serve multiple tasks in an async manner.

  • Don't call fire and forget methods - methods that don't return anything as your void methid code could be terminated anytime the original request ended to return the thread to the thread pool! If needed, use WebBackgrounder from http://nuget.org/packages/webBackgrounder

Check out these references:

Parallel Programming with .NET Blog
http://blogs.msdn.com/pfxteam/

Asynchrony in .NET Whitepaper
http://msdn.com/library/vstudio/hh191443.aspx

ASP.NET Async Tutorial
http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45

No comments:

Post a Comment