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!
Ad

More Related Content

What's hot (20)

Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
Cuelogic Technologies Pvt. Ltd.
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
網站系統安全及資料保護設計認知 2019
網站系統安全及資料保護設計認知 2019網站系統安全及資料保護設計認知 2019
網站系統安全及資料保護設計認知 2019
Justin Lin
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
React js basics
React js basicsReact js basics
React js basics
Maulik Shah
 
Selenium
SeleniumSelenium
Selenium
Adam Goucher
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
Bhagath Gopinath
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Protractor overview
Protractor overviewProtractor overview
Protractor overview
Abhishek Yadav
 
Introduction to Ionic framework
Introduction to Ionic frameworkIntroduction to Ionic framework
Introduction to Ionic framework
Shyjal Raazi
 
API Testing Presentations.pptx
API Testing Presentations.pptxAPI Testing Presentations.pptx
API Testing Presentations.pptx
ManmitSalunke
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
Erik van Appeldoorn
 
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
CodeOps Technologies LLP
 
POSTMAN.pptx
POSTMAN.pptxPOSTMAN.pptx
POSTMAN.pptx
RamaKrishna970827
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
Remo Jansen
 
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
iFunFactory Inc.
 
Node js
Node jsNode js
Node js
Fatih Şimşek
 
AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)
Brian Swartzfager
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Spring cloud
Spring cloudSpring cloud
Spring cloud
Milan Ashara
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
網站系統安全及資料保護設計認知 2019
網站系統安全及資料保護設計認知 2019網站系統安全及資料保護設計認知 2019
網站系統安全及資料保護設計認知 2019
Justin Lin
 
Asp.net mvc basic introduction
Asp.net mvc basic introductionAsp.net mvc basic introduction
Asp.net mvc basic introduction
Bhagath Gopinath
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Introduction to Ionic framework
Introduction to Ionic frameworkIntroduction to Ionic framework
Introduction to Ionic framework
Shyjal Raazi
 
API Testing Presentations.pptx
API Testing Presentations.pptxAPI Testing Presentations.pptx
API Testing Presentations.pptx
ManmitSalunke
 
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
AWS Lambda Hands-on: How to Create Phone Call Notifications in a Serverless W...
CodeOps Technologies LLP
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
Remo Jansen
 
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
[MGDC] 리눅스 게임 서버 성능 분석하기 - 아이펀팩토리 김진욱 CTO
iFunFactory Inc.
 
AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)
Brian Swartzfager
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 

Viewers also liked (12)

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

Similar to Asynchronous programming in ASP.NET (20)

10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
Malam Team
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
Smita B Kumar
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8
Thomas Robbins
 
Windows 8 Apps and the Outside World
Windows 8 Apps and the Outside WorldWindows 8 Apps and the Outside World
Windows 8 Apps and the Outside World
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
Pratik Khasnabis
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
Daniel Woods
 
Angular Owin Katana TypeScript
Angular Owin Katana TypeScriptAngular Owin Katana TypeScript
Angular Owin Katana TypeScript
Justin Wendlandt
 
Windows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside worldWindows 8 Metro apps and the outside world
Windows 8 Metro apps and the outside world
Prabhakaran Soundarapandian
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic Apps
Josh Lane
 
Orchestration service v2
Orchestration service v2Orchestration service v2
Orchestration service v2
Raman Gupta
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
deepak kumar
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
Prateek Maheshwari
 
10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster10 tips to make your ASP.NET Apps Faster
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
What's New in .Net 4.5
What's New in .Net 4.5What's New in .Net 4.5
What's New in .Net 4.5
Malam Team
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
Smita B Kumar
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8
Thomas Robbins
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
Daniel Woods
 
Angular Owin Katana TypeScript
Angular Owin Katana TypeScriptAngular Owin Katana TypeScript
Angular Owin Katana TypeScript
Justin Wendlandt
 
Workflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic AppsWorkflow All the Things with Azure Logic Apps
Workflow All the Things with Azure Logic Apps
Josh Lane
 
Orchestration service v2
Orchestration service v2Orchestration service v2
Orchestration service v2
Raman Gupta
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
Gary Yeh
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
Prateek Maheshwari
 
Ad

More from Alex Thissen (19)

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

Recently uploaded (20)

Adobe Photoshop Lightroom CC 2025 Crack Latest Version
Adobe Photoshop Lightroom CC 2025 Crack Latest VersionAdobe Photoshop Lightroom CC 2025 Crack Latest Version
Adobe Photoshop Lightroom CC 2025 Crack Latest Version
usmanhidray
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Mastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core PillarsMastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core Pillars
Marcel David
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Agentic AI Use Cases using GenAI LLM models
Agentic AI Use Cases using GenAI LLM modelsAgentic AI Use Cases using GenAI LLM models
Agentic AI Use Cases using GenAI LLM models
Manish Chopra
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Xforce Keygen 64-bit AutoCAD 2025 Crack
Xforce Keygen 64-bit AutoCAD 2025  CrackXforce Keygen 64-bit AutoCAD 2025  Crack
Xforce Keygen 64-bit AutoCAD 2025 Crack
usmanhidray
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Salesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdfSalesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdf
SRINIVASARAO PUSULURI
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
wareshashahzadiii
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Adobe Photoshop Lightroom CC 2025 Crack Latest Version
Adobe Photoshop Lightroom CC 2025 Crack Latest VersionAdobe Photoshop Lightroom CC 2025 Crack Latest Version
Adobe Photoshop Lightroom CC 2025 Crack Latest Version
usmanhidray
 
Sales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptxSales Deck SentinelOne Singularity Platform.pptx
Sales Deck SentinelOne Singularity Platform.pptx
EliandoLawnote
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Mastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core PillarsMastering OOP: Understanding the Four Core Pillars
Mastering OOP: Understanding the Four Core Pillars
Marcel David
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Agentic AI Use Cases using GenAI LLM models
Agentic AI Use Cases using GenAI LLM modelsAgentic AI Use Cases using GenAI LLM models
Agentic AI Use Cases using GenAI LLM models
Manish Chopra
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Xforce Keygen 64-bit AutoCAD 2025 Crack
Xforce Keygen 64-bit AutoCAD 2025  CrackXforce Keygen 64-bit AutoCAD 2025  Crack
Xforce Keygen 64-bit AutoCAD 2025 Crack
usmanhidray
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Salesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdfSalesforce Aged Complex Org Revitalization Process .pdf
Salesforce Aged Complex Org Revitalization Process .pdf
SRINIVASARAO PUSULURI
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
Minitab 22 Full Crack Plus Product Key Free Download [Latest] 2025
wareshashahzadiii
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 

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