SlideShare a Scribd company logo
1 of 31
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

What's hot

숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
VMware Tanzu Korea
 
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
MinGeun Park
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 

What's hot (20)

Mern stack developement
Mern stack developementMern stack developement
Mern stack developement
 
How To Become Better Engineer
How To Become Better EngineerHow To Become Better Engineer
How To Become Better Engineer
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Angular js
Angular jsAngular js
Angular js
 
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
[140315 박민근] 젠킨스를 이용한 자동빌드 시스템 구축하기(ci)
 
ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정ORM을 활용할 경우의 설계, 개발 과정
ORM을 활용할 경우의 설계, 개발 과정
 
REST API 설계
REST API 설계REST API 설계
REST API 설계
 
Api presentation
Api presentationApi presentation
Api presentation
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)
 
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 Grokking Techtalk #39: How to build an event driven architecture with Kafka ... Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
Grokking Techtalk #39: How to build an event driven architecture with Kafka ...
 
파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥
파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥
파이콘 한국 2019 - 파이썬으로 서버를 극한까지 끌어다 쓰기: Async I/O의 밑바닥
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 

Viewers also liked

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
 
Zappa_Brand_Jap_Pre
Zappa_Brand_Jap_PreZappa_Brand_Jap_Pre
Zappa_Brand_Jap_Pre
Marco Zappa
 

Viewers also liked (12)

DIABETES_E-Packet-2
DIABETES_E-Packet-2DIABETES_E-Packet-2
DIABETES_E-Packet-2
 
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
 
Ppt flashin
Ppt flashinPpt flashin
Ppt flashin
 
серкеноваулжан+кулинарнаяшкола+клиенты
серкеноваулжан+кулинарнаяшкола+клиентысеркеноваулжан+кулинарнаяшкола+клиенты
серкеноваулжан+кулинарнаяшкола+клиенты
 
Near_Neighbours_Coventry_University_Evaluation (1)
Near_Neighbours_Coventry_University_Evaluation (1)Near_Neighbours_Coventry_University_Evaluation (1)
Near_Neighbours_Coventry_University_Evaluation (1)
 
Padilla sosa lizeth_margarita_tarea3
Padilla sosa lizeth_margarita_tarea3Padilla sosa lizeth_margarita_tarea3
Padilla sosa lizeth_margarita_tarea3
 
хакимкаиргельды+компания+клиенты
хакимкаиргельды+компания+клиентыхакимкаиргельды+компания+клиенты
хакимкаиргельды+компания+клиенты
 
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
 
Padilla sosa lizeth_margarita_tarea12
Padilla sosa lizeth_margarita_tarea12Padilla sosa lizeth_margarita_tarea12
Padilla sosa lizeth_margarita_tarea12
 
Zappa_Brand_Jap_Pre
Zappa_Brand_Jap_PreZappa_Brand_Jap_Pre
Zappa_Brand_Jap_Pre
 
M ate3 multiplicacion
M ate3 multiplicacionM ate3 multiplicacion
M ate3 multiplicacion
 
CV.DOC
CV.DOCCV.DOC
CV.DOC
 

Similar to Asynchronous programming in ASP.NET

End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 

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
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
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)
 
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)
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
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...
 
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
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Advance java session 20
Advance java session 20Advance java session 20
Advance java session 20
 
Using MVC with Kentico 8
Using MVC with Kentico 8Using MVC with Kentico 8
Using MVC with Kentico 8
 
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
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Ratpack Web Framework
Ratpack Web FrameworkRatpack Web Framework
Ratpack Web Framework
 
Angular Owin Katana TypeScript
Angular Owin Katana TypeScriptAngular Owin Katana TypeScript
Angular Owin Katana TypeScript
 
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
 
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
 
Orchestration service v2
Orchestration service v2Orchestration service v2
Orchestration service v2
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
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
 

More from 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
 

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
 
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
 
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
 
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
 
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
 
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 - ...
 
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
 
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
 
Exploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft LandscapeExploring Microservices in a Microsoft Landscape
Exploring Microservices in a Microsoft Landscape
 
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
 
Visual Studio Productivity tips
Visual Studio Productivity tipsVisual Studio Productivity tips
Visual Studio Productivity tips
 
Exploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscapeExploring microservices in a Microsoft landscape
Exploring microservices in a Microsoft landscape
 
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
 
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
 
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
 
//customer/
//customer///customer/
//customer/
 
ASP.NET vNext
ASP.NET vNextASP.NET vNext
ASP.NET vNext
 
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!
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 

Recently uploaded

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 

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

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