SlideShare a Scribd company logo
Asynchronous
programming in ASP.NET
Name:
Role:
https://nl.linkedin.com/in/alexthissen
@alexthissen
http://blog.alexthissen.nl
Alex Thissen
Lead Consultant, Xpirit
Introducing myself
Agenda
• Introduction on synchronicity
• Threading and async programming in .NET
• Details for
• ASP.NET WebForms
• ASP.NET MVC
• ASP.NET WebAPI
• ASP.NET SignalR
• Gotchas
• Questions and Answers
Talking about
synchronicity
Primer on async and multi-threading in Windows and .NET
(A)Synchronous in a web world
Message
Exchange
Patterns
Parallelization
vs. multi-
threading
High Latency
vs high
throughput
Asynchronicity
is easy now
Blocking
operations
Asynchronous
is faster
A tale of fast food restaurants
Threading in Windows and .NET
• Two concurrency types in Windows Operating
System
1. Worker threads
Physical units of work
2. IO Completion Ports
Special construct for async
I/O bound operations
• Threads incur overhead
• But threads waiting for IO Completion Port are efficient
.NET Threading primitives
• System.Threading namespace
• Threads: Thread and ThreadPool
• Locks: Mutex, WaitHandle, Semaphore, Monitor, Interlocked
• ThreadPool cannot scale hard
(2 extra threads/second)
• Each .NET logical thread adds overhead
(1MB of managed memory)
.NET 4.5 Worker Threads Completion Port
Threads
Minimum 4 4
Maximum 5000 (4095) 1000
Threading in ASP.NET
Application Pool (w3wp.exe)
CLR Threadpool
Request Queue
AppDomain
Website
http.sys
IIS
Unmanaged execution
Kernel level
… …
Global Queue
connectionManagement
maxconnection
httpRuntime/
minFreeThreads
minLocalRequestFreeThreads
processModel/
maxWorkerThreads
minWorkerThreads
maxIoThreads
Outgoing connections
applicationPool/
maxConcurrentRequestsPerCpu
Worker
Threads
Completion
Port Threads
Making a choice for (a)sync
Synchronous
• Operations are simple or
short-running
• Simplicity over efficiency
• CPU-bound operations
Asynchronous
• Ability to cancel long-
running tasks
• Parallelism over simplicity
• Blocking operations are
bottleneck for
performance
• Network or I/O bound
operations
Worker thread #1 Worker thread #2Worker thread #3 IO Completion Port
Thread #3
Threads types and context switches
ASP.NET
Runtime
Store
Customers
Async
Windows IO
Completion
Port
db.Save
ChangesAsync
Must support async pattern
in some way
As an example,
Entity Framework 6 has
support for async operations
Unnecessary additional
threads only occur overhead.
Underlying SqlClient uses IO
Completion Port for async I/O
operation
Asynchronous
programming
.NET Framework support for async
History of .NET async programming
Asynchronous Programming ModelAPM
• Pairs of Begin/End methods
• Example: FileStream.BeginWrite and FileStream.EndWrite
• Convert using TaskFactory and TaskFactory<TResult>
Event-based Asynchronous PatternEAP
• Pairs of OperationAsync method and OperationCompleted event
• Example: WebClient.DownloadStringAsync and WebClient.DownloadStringCompleted
• TaskCompletionSource<T> to the rescue
Task-based Asynchronous PatternTAP
• Task and Task<T>
• Preferred model
Async in .NET BCL classes
• .NET Framework classes show each async style
• Sometimes even mixed
• Example: System.Net.WebClient
• TPL (Task-based) APIs are preferred
• Find and use new classes that support TAP natively
Async constructs in ASP.NET
• ASP.NET runtime
• Async Modules
• Async Handlers
• ASP.NET WebForms
• AddOnPreRenderComplete
• PageAsyncTask
• ASP.NET MVC and WebAPI
• Async actions
ASP.NET WebForms
ASP.NET specifics part 1
Asynchronous programming in
WebForms
Your options:
1. Asynchronous
pages
2. AsyncTasks
It all comes down to hooking into async page lifecycle
Normal synchronous page lifecycle
for ASP.NET WebForms
…
…
LoadComplete
PreRender
PreRenderComplete
SaveViewState
Client
Request
page
Send response
Render
…
Thread 1
Switch to asynchronous handling
…
…
LoadComplete
PreRender
PreRenderComplete
SaveViewState
Client
Send response
Render
…
Thread 1
Thread 2
IAsyncResult
Request
page
Async pages in WebForms
Recipe for async pages
• Add async="true" to @Page directive or <pages> element in
web.config
• Pass delegates for start and completion of asynchronous operation
in AddOnPreRenderCompleteAsync method
• Register event handler for PreRenderComplete
private void Page_Load(object sender, EventArgs e)
{
this.AddOnPreRenderCompleteAsync(
new BeginEventHandler(BeginAsynchronousOperation),
new EndEventHandler(EndAsynchronousOperation));
this.PreRenderComplete += new
EventHandler(LongRunningAsync_PreRenderComplete);
}
PageAsyncTasks
• Single unit of work
• Encapsulated by PageAsyncTask class
• Support for APM and TPL (new in ASP.NET 4.5)
• Preferred way over async void event handlers
• Can run multiple tasks in parallel
// TAP async delegate as Page task
RegisterAsyncTask(new PageAsyncTask(async (token) =>
{
await Task.Delay(3000, token);
}));
ASP.NET MVC and
WebAPI
ASP.NET specifics part 2
Async support in MVC
• AsyncController (MVC3+)
• Split actions in two parts
1. Starting async: void IndexAsync()
2. Completing async: ActionResult IndexCompleted(…)
• AsyncManager
• OutstandingOperations Increment and Decrement
• Task and Task<ActionResult> (MVC 4+)
• Async and await (C# 5+)
Async actions in ASP.NET MVC
From synchronous
public ActionResult Index()
{
// Call synchronous operations
return View("Index", GetResults());
}
To asynchronous
public async Task<ActionResult> IndexAsync()
{
// Call operations asynchronously
return View("Index", await GetResultsAsync());
}
Timeouts
• Timeouts apply to synchronous handlers
• Default timeout is 110 seconds
(90 for ASP.NET 1.0 and 1.1)
• MVC and WebAPI are always asynchronous
• Even if you only use synchronous handlers
• (Server script) timeouts do not apply
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5" executionTimeout="5000" />
</system.web>
Timeouts in MVC and WebAPI
• Use AsyncTimeoutAttribute on async actions
• When timeout occurs TimeoutException is thrown
from action
• Default timeout is AsyncManager’s 45000 milliseconds
• Might want to catch errors
[AsyncTimeout(2000)]
[HandleError(ExceptionType=typeof(TimeoutException))]
public async Task<ActionResult> SomeMethodAsync(CancellationToken token)
{
// Pass down CancellationToken to other async method calls
…
}
ASP.NET SignalR async notes
• In-memory message bus is very fast
• Team decided not to make it async
• Sending to clients is
• always asynchronous
• on different call-stack
Beware of the async gotchas
• Cannot catch exceptions in async void methods
• Mixing sync/async can deadlock threads in ASP.NET
• Suboptimal performance for regular awaits
Best practices for async:
• Avoid async void
• Async all the way
• Configure your wait
Tips
• Don’t do 3 gotcha’s
• Avoid blocking threads and thread starvation
• Remember I/O bound (await)
vs. CPU bound (ThreadPool, Task.Run, Parallel.For)
• Thread management:
• Avoid creating too many
• Create where needed and reuse if possible
• Try to switch to IO Completion Port threads
• Look for BCL support
Summary
• Make sure you are comfortable with
• Multi-threading, parallelism, concurrency, async and await
• ASP.NET fully supports TPL and async/await
• WebForms
• MVC
• WebAPI
• Great performance and scalability comes from
good thread management
• Be aware of specific ASP.NET behavior
Questions? Answers!

More Related Content

Viewers also liked (12)

PDF
DIABETES_E-Packet-2
Julia Kuhlberg
 
PPTX
Async Programming with C#5: Basics and Pitfalls
EastBanc Tachnologies
 
PPTX
Ppt flashin
bisnis terbaru
 
PPT
серкеноваулжан+кулинарнаяшкола+клиенты
Улжан Серкенова
 
PDF
Near_Neighbours_Coventry_University_Evaluation (1)
Tom Fisher
 
PDF
Padilla sosa lizeth_margarita_tarea3
Lizeth Padilla
 
PPTX
хакимкаиргельды+компания+клиенты
Хаким Каиргельды
 
PPTX
Comment intégrer les switch Nebula à votre réseau
Zyxel France
 
PPTX
Padilla sosa lizeth_margarita_tarea12
Lizeth Padilla
 
ODP
Zappa_Brand_Jap_Pre
Marco Zappa
 
PDF
M ate3 multiplicacion
Lizeth Padilla
 
DOC
CV.DOC
Allan Nilsson
 
DIABETES_E-Packet-2
Julia Kuhlberg
 
Async Programming with C#5: Basics and Pitfalls
EastBanc Tachnologies
 
Ppt flashin
bisnis terbaru
 
серкеноваулжан+кулинарнаяшкола+клиенты
Улжан Серкенова
 
Near_Neighbours_Coventry_University_Evaluation (1)
Tom Fisher
 
Padilla sosa lizeth_margarita_tarea3
Lizeth Padilla
 
хакимкаиргельды+компания+клиенты
Хаким Каиргельды
 
Comment intégrer les switch Nebula à votre réseau
Zyxel France
 
Padilla sosa lizeth_margarita_tarea12
Lizeth Padilla
 
Zappa_Brand_Jap_Pre
Marco Zappa
 
M ate3 multiplicacion
Lizeth Padilla
 

Similar to Asynchronous programming in ASP.NET (20)

PPTX
End to-end async and await
vfabro
 
PPSX
Async-await best practices in 10 minutes
Paulo Morgado
 
PPTX
C# 5 deep drive into asynchronous programming
Praveen Prajapati
 
PPTX
Async and Await on the Server
Doug Jones
 
PPTX
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
PPTX
History of asynchronous in .NET
Marcin Tyborowski
 
PPTX
Async await
Jeff Hart
 
PPTX
Async ASP.NET Applications
Shayne Boyer
 
PPTX
Async programming in c#
Ahasanul Kalam Akib
 
PDF
Async Await for Mobile Apps
Craig Dunn
 
PPT
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
PPTX
MobConf - session on C# async-await on 18june2016 at Kochi
Praveen Nair
 
PPTX
Async in .NET
RTigger
 
PPTX
Workshop: Async and Parallel in C#
Rainer Stropek
 
PPTX
Training – Going Async
Betclic Everest Group Tech Team
 
PPT
Web services, WCF services and Multi Threading with Windows Forms
Peter Gfader
 
PPTX
Async/Await
Jeff Hart
 
PPTX
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 
PPTX
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
PDF
Why async matters
timbc
 
End to-end async and await
vfabro
 
Async-await best practices in 10 minutes
Paulo Morgado
 
C# 5 deep drive into asynchronous programming
Praveen Prajapati
 
Async and Await on the Server
Doug Jones
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
History of asynchronous in .NET
Marcin Tyborowski
 
Async await
Jeff Hart
 
Async ASP.NET Applications
Shayne Boyer
 
Async programming in c#
Ahasanul Kalam Akib
 
Async Await for Mobile Apps
Craig Dunn
 
Evolution of asynchrony in (ASP).NET
Aliaksandr Famin
 
MobConf - session on C# async-await on 18june2016 at Kochi
Praveen Nair
 
Async in .NET
RTigger
 
Workshop: Async and Parallel in C#
Rainer Stropek
 
Training – Going Async
Betclic Everest Group Tech Team
 
Web services, WCF services and Multi Threading with Windows Forms
Peter Gfader
 
Async/Await
Jeff Hart
 
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
Why async matters
timbc
 
Ad

More from Alex Thissen (19)

PPTX
Go (con)figure - Making sense of .NET configuration
Alex Thissen
 
PPTX
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Alex Thissen
 
PPTX
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Alex Thissen
 
PPTX
Health monitoring and dependency injection - CNUG November 2019
Alex Thissen
 
PPTX
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Alex Thissen
 
PPTX
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
Alex Thissen
 
PPTX
It depends: Loving .NET Core dependency injection or not
Alex Thissen
 
PPTX
Overview of the new .NET Core and .NET Platform Standard
Alex Thissen
 
PPTX
Exploring Microservices in a Microsoft Landscape
Alex Thissen
 
PPTX
How Docker and ASP.NET Core will change the life of a Microsoft developer
Alex Thissen
 
PPTX
Visual Studio Productivity tips
Alex Thissen
 
PPTX
Exploring microservices in a Microsoft landscape
Alex Thissen
 
PPTX
Visual Studio 2015 experts tips and tricks
Alex Thissen
 
PPTX
ASP.NET 5 - Microsoft's Web development platform reimagined
Alex Thissen
 
PPTX
MVC 6 - the new unified Web programming model
Alex Thissen
 
PPTX
//customer/
Alex Thissen
 
PPTX
ASP.NET vNext
Alex Thissen
 
PPTX
Run your Dockerized ASP.NET application on Windows and Linux!
Alex Thissen
 
PPTX
.NET Core: a new .NET Platform
Alex Thissen
 
Go (con)figure - Making sense of .NET configuration
Alex Thissen
 
Logging, tracing and metrics: Instrumentation in .NET 5 and Azure
Alex Thissen
 
Logging tracing and metrics in .NET Core and Azure - dotnetdays 2020
Alex Thissen
 
Health monitoring and dependency injection - CNUG November 2019
Alex Thissen
 
Architecting .NET solutions in a Docker ecosystem - .NET Fest Kyiv 2019
Alex Thissen
 
I dont feel so well. Integrating health checks in your .NET Core solutions - ...
Alex Thissen
 
It depends: Loving .NET Core dependency injection or not
Alex Thissen
 
Overview of the new .NET Core and .NET Platform Standard
Alex Thissen
 
Exploring Microservices in a Microsoft Landscape
Alex Thissen
 
How Docker and ASP.NET Core will change the life of a Microsoft developer
Alex Thissen
 
Visual Studio Productivity tips
Alex Thissen
 
Exploring microservices in a Microsoft landscape
Alex Thissen
 
Visual Studio 2015 experts tips and tricks
Alex Thissen
 
ASP.NET 5 - Microsoft's Web development platform reimagined
Alex Thissen
 
MVC 6 - the new unified Web programming model
Alex Thissen
 
//customer/
Alex Thissen
 
ASP.NET vNext
Alex Thissen
 
Run your Dockerized ASP.NET application on Windows and Linux!
Alex Thissen
 
.NET Core: a new .NET Platform
Alex Thissen
 
Ad

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Import Data Form Excel to Tally Services
Tally xperts
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 

Asynchronous programming in ASP.NET

  • 3. Agenda • Introduction on synchronicity • Threading and async programming in .NET • Details for • ASP.NET WebForms • ASP.NET MVC • ASP.NET WebAPI • ASP.NET SignalR • Gotchas • Questions and Answers
  • 4. Talking about synchronicity Primer on async and multi-threading in Windows and .NET
  • 5. (A)Synchronous in a web world Message Exchange Patterns Parallelization vs. multi- threading High Latency vs high throughput Asynchronicity is easy now Blocking operations Asynchronous is faster
  • 6. A tale of fast food restaurants
  • 7. Threading in Windows and .NET • Two concurrency types in Windows Operating System 1. Worker threads Physical units of work 2. IO Completion Ports Special construct for async I/O bound operations • Threads incur overhead • But threads waiting for IO Completion Port are efficient
  • 8. .NET Threading primitives • System.Threading namespace • Threads: Thread and ThreadPool • Locks: Mutex, WaitHandle, Semaphore, Monitor, Interlocked • ThreadPool cannot scale hard (2 extra threads/second) • Each .NET logical thread adds overhead (1MB of managed memory) .NET 4.5 Worker Threads Completion Port Threads Minimum 4 4 Maximum 5000 (4095) 1000
  • 9. Threading in ASP.NET Application Pool (w3wp.exe) CLR Threadpool Request Queue AppDomain Website http.sys IIS Unmanaged execution Kernel level … … Global Queue connectionManagement maxconnection httpRuntime/ minFreeThreads minLocalRequestFreeThreads processModel/ maxWorkerThreads minWorkerThreads maxIoThreads Outgoing connections applicationPool/ maxConcurrentRequestsPerCpu Worker Threads Completion Port Threads
  • 10. Making a choice for (a)sync Synchronous • Operations are simple or short-running • Simplicity over efficiency • CPU-bound operations Asynchronous • Ability to cancel long- running tasks • Parallelism over simplicity • Blocking operations are bottleneck for performance • Network or I/O bound operations
  • 11. Worker thread #1 Worker thread #2Worker thread #3 IO Completion Port Thread #3 Threads types and context switches ASP.NET Runtime Store Customers Async Windows IO Completion Port db.Save ChangesAsync Must support async pattern in some way As an example, Entity Framework 6 has support for async operations Unnecessary additional threads only occur overhead. Underlying SqlClient uses IO Completion Port for async I/O operation
  • 13. History of .NET async programming Asynchronous Programming ModelAPM • Pairs of Begin/End methods • Example: FileStream.BeginWrite and FileStream.EndWrite • Convert using TaskFactory and TaskFactory<TResult> Event-based Asynchronous PatternEAP • Pairs of OperationAsync method and OperationCompleted event • Example: WebClient.DownloadStringAsync and WebClient.DownloadStringCompleted • TaskCompletionSource<T> to the rescue Task-based Asynchronous PatternTAP • Task and Task<T> • Preferred model
  • 14. Async in .NET BCL classes • .NET Framework classes show each async style • Sometimes even mixed • Example: System.Net.WebClient • TPL (Task-based) APIs are preferred • Find and use new classes that support TAP natively
  • 15. Async constructs in ASP.NET • ASP.NET runtime • Async Modules • Async Handlers • ASP.NET WebForms • AddOnPreRenderComplete • PageAsyncTask • ASP.NET MVC and WebAPI • Async actions
  • 17. Asynchronous programming in WebForms Your options: 1. Asynchronous pages 2. AsyncTasks It all comes down to hooking into async page lifecycle
  • 18. Normal synchronous page lifecycle for ASP.NET WebForms … … LoadComplete PreRender PreRenderComplete SaveViewState Client Request page Send response Render … Thread 1
  • 19. Switch to asynchronous handling … … LoadComplete PreRender PreRenderComplete SaveViewState Client Send response Render … Thread 1 Thread 2 IAsyncResult Request page
  • 20. Async pages in WebForms Recipe for async pages • Add async="true" to @Page directive or <pages> element in web.config • Pass delegates for start and completion of asynchronous operation in AddOnPreRenderCompleteAsync method • Register event handler for PreRenderComplete private void Page_Load(object sender, EventArgs e) { this.AddOnPreRenderCompleteAsync( new BeginEventHandler(BeginAsynchronousOperation), new EndEventHandler(EndAsynchronousOperation)); this.PreRenderComplete += new EventHandler(LongRunningAsync_PreRenderComplete); }
  • 21. PageAsyncTasks • Single unit of work • Encapsulated by PageAsyncTask class • Support for APM and TPL (new in ASP.NET 4.5) • Preferred way over async void event handlers • Can run multiple tasks in parallel // TAP async delegate as Page task RegisterAsyncTask(new PageAsyncTask(async (token) => { await Task.Delay(3000, token); }));
  • 22. ASP.NET MVC and WebAPI ASP.NET specifics part 2
  • 23. Async support in MVC • AsyncController (MVC3+) • Split actions in two parts 1. Starting async: void IndexAsync() 2. Completing async: ActionResult IndexCompleted(…) • AsyncManager • OutstandingOperations Increment and Decrement • Task and Task<ActionResult> (MVC 4+) • Async and await (C# 5+)
  • 24. Async actions in ASP.NET MVC From synchronous public ActionResult Index() { // Call synchronous operations return View("Index", GetResults()); } To asynchronous public async Task<ActionResult> IndexAsync() { // Call operations asynchronously return View("Index", await GetResultsAsync()); }
  • 25. Timeouts • Timeouts apply to synchronous handlers • Default timeout is 110 seconds (90 for ASP.NET 1.0 and 1.1) • MVC and WebAPI are always asynchronous • Even if you only use synchronous handlers • (Server script) timeouts do not apply <system.web> <compilation debug="true" targetFramework="4.5"/> <httpRuntime targetFramework="4.5" executionTimeout="5000" /> </system.web>
  • 26. Timeouts in MVC and WebAPI • Use AsyncTimeoutAttribute on async actions • When timeout occurs TimeoutException is thrown from action • Default timeout is AsyncManager’s 45000 milliseconds • Might want to catch errors [AsyncTimeout(2000)] [HandleError(ExceptionType=typeof(TimeoutException))] public async Task<ActionResult> SomeMethodAsync(CancellationToken token) { // Pass down CancellationToken to other async method calls … }
  • 27. ASP.NET SignalR async notes • In-memory message bus is very fast • Team decided not to make it async • Sending to clients is • always asynchronous • on different call-stack
  • 28. Beware of the async gotchas • Cannot catch exceptions in async void methods • Mixing sync/async can deadlock threads in ASP.NET • Suboptimal performance for regular awaits Best practices for async: • Avoid async void • Async all the way • Configure your wait
  • 29. Tips • Don’t do 3 gotcha’s • Avoid blocking threads and thread starvation • Remember I/O bound (await) vs. CPU bound (ThreadPool, Task.Run, Parallel.For) • Thread management: • Avoid creating too many • Create where needed and reuse if possible • Try to switch to IO Completion Port threads • Look for BCL support
  • 30. Summary • Make sure you are comfortable with • Multi-threading, parallelism, concurrency, async and await • ASP.NET fully supports TPL and async/await • WebForms • MVC • WebAPI • Great performance and scalability comes from good thread management • Be aware of specific ASP.NET behavior

Editor's Notes

  • #10: http://support.microsoft.com/kb/821268
  • #11: http://www.asp.net/web-forms/overview/performance-and-caching/using-asynchronous-methods-in-aspnet-45
  • #22: http://blogs.msdn.com/b/pfxteam/archive/2012/05/31/what-s-new-for-parallelism-in-visual-studio-2012-rc.aspx
  • #28: http://stackoverflow.com/questions/19193451/should-signalr-server-side-methods-be-async-when-calling-clients
  • #29: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx