SlideShare a Scribd company logo
1 of 28
Matteo Baglini
Software Architect/Developer, Freelance
Email: matteo.baglini@gmail.com
Web: http://www.makesimple.net
Blog: http://blogs.ugidotnet.org/bmatte
«.NET: applicazioni veloci
come la luce. Scopri come
velocizzare le applicazioni
 con la programmazione
        asincrona»

                              2
«Programmazione asincrona e
  programmazione parallela
       sono sinonimi»


                          3
Windows

          4
Thread

         5
Thread
Madness
          6
Modern CPU

             7
Asynchronous

               8
Parallel

           9
CPU-Bound

            10
CLR Thread Pool - UserWorkItem

         Global
         Queue
         (FIFO)




                   Worker    …    Worker
                  Thread 1       Thread N


Work1 Program
 Work2
      Thread
CLR Thread Pool - Tasks
                         Local           Local
                         Queue     …     Queue
          Global            1               N
          Queue          (LIFO)          (LIFO)
          (FIFO)




                       Worker     …     Worker
                      Thread 1         Thread N
                                        Task 6
Task 1 Program     Task Task 3
                        4
 Task 2                  Task 5
      Thread
I/O-Bound

            13
var readed = fileStream.Read(buff, 0, buff.Length);




               ReadFile(hFile, Buff, BUFFSIZE-1, &dwReaded, NULL);




                            Windows I/O Subsystem




Thread
                                      Hardward does I/O.
block, waits
                                      No threads involved!
for I/O
completion.                                                          14
fileStream.BeginRead(buff, 0, buff.Length, cb, null);

                           void EndReadCb(IAsyncResult asyncResult) {…}



                   ReadFile(hFile, Buff, BUFFSIZE-1, &dwReaded, NULL);




                                 Windows I/O Subsystem



                                                           ThreadPool
Hardward does
I/O. No threads                                             I/O
involved!                                                   Completion
                                                            Ports
                                                                          15
App Threading
   Models
            16
while ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
      if (bRet == -1) {
             // handle error / exit
      }
      else {
             TranslateMessage(&msg);
             DispatchMessage(&msg);
      }
}



                                                        17
Parallel

           18
Async/Await

              19
Coroutine

            20
WinRT

        21
22
23
•    Principio:
    • Non bloccare i Thread.
•    Pattern:
    • Operazioni I/O-bound: conviene
       sempre effettuarle in asincrono.
    • Operazioni CPU-bound: dipende
       dal contesto e dal costo
       (computazionale).
                                          24
Primary    Secondary    Parent/                                               Return/
  Model                                       Progress        Cancel    Wait   Timeout
              Use         Use        Child                                               Exception


Queue
           CPU        Sync I/O      No        No         No             No     No        No
WorkItem


                      CPU via
APM        I/O                      No        No         No             Si     No        Si
                      BeginInvoke

                      CPU via
EAP        I/O        Background    No        Alcuni     Alcuni         No     No        Si
                      Worker

                                                         Si, via
                      Sync I/O or
TAP        CPU                      Si        No         Cooperative    Si     Si        Si
                      FromAsync
                                                         Cancellation

                                                         Si, via
Timer      CPU        Sync I/O      No        No                        No     Si        No
                                                         Dispose


                                                                                                25
26
•   The Task-based Asynchronous Pattern
•   Asynchronous Programming in C# and
    Visual Basic
•   Diving deep with WinRT and await

•   http://blogs.msdn.com/b/pfxteam
•   http://blogs.msdn.com/b/dotnet/

•   101 Async Samples

                                          27
Asynchronous Programming Lab @ DotNetToscana

More Related Content

What's hot (13)

OpenMP
OpenMPOpenMP
OpenMP
 
Open mp intro_01
Open mp intro_01Open mp intro_01
Open mp intro_01
 
Intro to OpenMP
Intro to OpenMPIntro to OpenMP
Intro to OpenMP
 
The pocl Kernel Compiler
The pocl Kernel CompilerThe pocl Kernel Compiler
The pocl Kernel Compiler
 
IPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-onIPv4aaS tutorial and hands-on
IPv4aaS tutorial and hands-on
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Qemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System EmulationQemu JIT Code Generator and System Emulation
Qemu JIT Code Generator and System Emulation
 
CLR threads
CLR threadsCLR threads
CLR threads
 
How Functions Work
How Functions WorkHow Functions Work
How Functions Work
 
introduction to java
introduction to javaintroduction to java
introduction to java
 
Planet of the AOPs
Planet of the AOPsPlanet of the AOPs
Planet of the AOPs
 
FreeRTOS Course - Queue Management
FreeRTOS Course - Queue ManagementFreeRTOS Course - Queue Management
FreeRTOS Course - Queue Management
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 

Similar to Asynchronous Programming Lab @ DotNetToscana

Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsDaniel Blezek
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSkills Matter
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futureTakayuki Muranushi
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringScyllaDB
 
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...CODE BLUE
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programmingIskren Chernev
 
Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015Boey Pak Cheong
 
lec5 - The processor.pptx
lec5 - The processor.pptxlec5 - The processor.pptx
lec5 - The processor.pptxMahadevaAH
 
Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with pythonPatrick Vergain
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfKrystian Zybała
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experimentAmos Wenger
 

Similar to Asynchronous Programming Lab @ DotNetToscana (20)

Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
High-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uringHigh-Performance Networking Using eBPF, XDP, and io_uring
High-Performance Networking Using eBPF, XDP, and io_uring
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
7 seg
7 seg7 seg
7 seg
 
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
[CB16] COFI break – Breaking exploits with Processor trace and Practical cont...
 
Pipelining In computer
Pipelining In computer Pipelining In computer
Pipelining In computer
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015Concurrency and Python - PyCon MY 2015
Concurrency and Python - PyCon MY 2015
 
lec5 - The processor.pptx
lec5 - The processor.pptxlec5 - The processor.pptx
lec5 - The processor.pptx
 
Multiprocessing with python
Multiprocessing with pythonMultiprocessing with python
Multiprocessing with python
 
Assembly p1
Assembly p1Assembly p1
Assembly p1
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Cis82 e2-1-packet forwarding
Cis82 e2-1-packet forwardingCis82 e2-1-packet forwarding
Cis82 e2-1-packet forwarding
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 

More from Matteo Baglini

Legacy Coderetreat Bologna @ CodersTUG
Legacy Coderetreat Bologna @ CodersTUGLegacy Coderetreat Bologna @ CodersTUG
Legacy Coderetreat Bologna @ CodersTUGMatteo Baglini
 
Approval Tests @ MiniIAD
Approval Tests @ MiniIADApproval Tests @ MiniIAD
Approval Tests @ MiniIADMatteo Baglini
 
VS13 - Approval Tests: cosa, come, quando, perché? @ CDays
VS13 - Approval Tests: cosa, come, quando, perché? @ CDaysVS13 - Approval Tests: cosa, come, quando, perché? @ CDays
VS13 - Approval Tests: cosa, come, quando, perché? @ CDaysMatteo Baglini
 
Approval Tests @ CodersTUG
Approval Tests @ CodersTUGApproval Tests @ CodersTUG
Approval Tests @ CodersTUGMatteo Baglini
 
Coderetreat @ CodersTUG
Coderetreat @ CodersTUGCoderetreat @ CodersTUG
Coderetreat @ CodersTUGMatteo Baglini
 
RESTFul Web API Services @ DotNetToscana
RESTFul Web API Services @ DotNetToscanaRESTFul Web API Services @ DotNetToscana
RESTFul Web API Services @ DotNetToscanaMatteo Baglini
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaMatteo Baglini
 
Async: scalabilità e responsiveness senza pari! @ CDays
Async: scalabilità e responsiveness senza pari! @ CDaysAsync: scalabilità e responsiveness senza pari! @ CDays
Async: scalabilità e responsiveness senza pari! @ CDaysMatteo Baglini
 
The NoSQL movement @ DotNetToscana
The NoSQL movement @ DotNetToscanaThe NoSQL movement @ DotNetToscana
The NoSQL movement @ DotNetToscanaMatteo Baglini
 
Key-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscanaKey-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscanaMatteo Baglini
 

More from Matteo Baglini (11)

Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
 
Legacy Coderetreat Bologna @ CodersTUG
Legacy Coderetreat Bologna @ CodersTUGLegacy Coderetreat Bologna @ CodersTUG
Legacy Coderetreat Bologna @ CodersTUG
 
Approval Tests @ MiniIAD
Approval Tests @ MiniIADApproval Tests @ MiniIAD
Approval Tests @ MiniIAD
 
VS13 - Approval Tests: cosa, come, quando, perché? @ CDays
VS13 - Approval Tests: cosa, come, quando, perché? @ CDaysVS13 - Approval Tests: cosa, come, quando, perché? @ CDays
VS13 - Approval Tests: cosa, come, quando, perché? @ CDays
 
Approval Tests @ CodersTUG
Approval Tests @ CodersTUGApproval Tests @ CodersTUG
Approval Tests @ CodersTUG
 
Coderetreat @ CodersTUG
Coderetreat @ CodersTUGCoderetreat @ CodersTUG
Coderetreat @ CodersTUG
 
RESTFul Web API Services @ DotNetToscana
RESTFul Web API Services @ DotNetToscanaRESTFul Web API Services @ DotNetToscana
RESTFul Web API Services @ DotNetToscana
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
Async: scalabilità e responsiveness senza pari! @ CDays
Async: scalabilità e responsiveness senza pari! @ CDaysAsync: scalabilità e responsiveness senza pari! @ CDays
Async: scalabilità e responsiveness senza pari! @ CDays
 
The NoSQL movement @ DotNetToscana
The NoSQL movement @ DotNetToscanaThe NoSQL movement @ DotNetToscana
The NoSQL movement @ DotNetToscana
 
Key-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscanaKey-value databases in practice Redis @ DotNetToscana
Key-value databases in practice Redis @ DotNetToscana
 

Recently uploaded

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Asynchronous Programming Lab @ DotNetToscana

  • 1. Matteo Baglini Software Architect/Developer, Freelance Email: matteo.baglini@gmail.com Web: http://www.makesimple.net Blog: http://blogs.ugidotnet.org/bmatte
  • 2. «.NET: applicazioni veloci come la luce. Scopri come velocizzare le applicazioni con la programmazione asincrona» 2
  • 3. «Programmazione asincrona e programmazione parallela sono sinonimi» 3
  • 5. Thread 5
  • 10. CPU-Bound 10
  • 11. CLR Thread Pool - UserWorkItem Global Queue (FIFO) Worker … Worker Thread 1 Thread N Work1 Program Work2 Thread
  • 12. CLR Thread Pool - Tasks Local Local Queue … Queue Global 1 N Queue (LIFO) (LIFO) (FIFO) Worker … Worker Thread 1 Thread N Task 6 Task 1 Program Task Task 3 4 Task 2 Task 5 Thread
  • 13. I/O-Bound 13
  • 14. var readed = fileStream.Read(buff, 0, buff.Length); ReadFile(hFile, Buff, BUFFSIZE-1, &dwReaded, NULL); Windows I/O Subsystem Thread Hardward does I/O. block, waits No threads involved! for I/O completion. 14
  • 15. fileStream.BeginRead(buff, 0, buff.Length, cb, null); void EndReadCb(IAsyncResult asyncResult) {…} ReadFile(hFile, Buff, BUFFSIZE-1, &dwReaded, NULL); Windows I/O Subsystem ThreadPool Hardward does I/O. No threads I/O involved! Completion Ports 15
  • 16. App Threading Models 16
  • 17. while ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { if (bRet == -1) { // handle error / exit } else { TranslateMessage(&msg); DispatchMessage(&msg); } } 17
  • 18. Parallel 18
  • 20. Coroutine 20
  • 21. WinRT 21
  • 22. 22
  • 23. 23
  • 24. Principio: • Non bloccare i Thread. • Pattern: • Operazioni I/O-bound: conviene sempre effettuarle in asincrono. • Operazioni CPU-bound: dipende dal contesto e dal costo (computazionale). 24
  • 25. Primary Secondary Parent/ Return/ Model Progress Cancel Wait Timeout Use Use Child Exception Queue CPU Sync I/O No No No No No No WorkItem CPU via APM I/O No No No Si No Si BeginInvoke CPU via EAP I/O Background No Alcuni Alcuni No No Si Worker Si, via Sync I/O or TAP CPU Si No Cooperative Si Si Si FromAsync Cancellation Si, via Timer CPU Sync I/O No No No Si No Dispose 25
  • 26. 26
  • 27. The Task-based Asynchronous Pattern • Asynchronous Programming in C# and Visual Basic • Diving deep with WinRT and await • http://blogs.msdn.com/b/pfxteam • http://blogs.msdn.com/b/dotnet/ • 101 Async Samples 27

Editor's Notes

  1. Prima di andareavanticapiamomeglio come operanoi Worker Thread del ThreadPool. QuandovieneinvocatoilmetodoQueueUserWorkItemdellaclasseThreadPoolilrelativoWorkItemvienemesso in una coda di lavoroglobale.Ogni Worker Thread cerca di prelevare un item usando un algoritmo di tipo FIFO.Unavoltapreso in carico, ilWorkItem, vienesemplicementeeseguito.Quando un Worker Thread terminal’esecuzione del WorkItemverifica se ci sonoaltrielementinella coda, se ci sono continua a prelevare, mentre se non ci sonosiimposta in Sleep.Passato un certo lasso di tempo il Worker Thread sisveglia e si auto termina in modo da liberare le risorse.Datoche la coda come dice ilnomestesso è globalel’accessoavviene in manieraconcorrentequindic’è un elevatorischio di conflitto.Nellevecchieversioni del framework l’accesso a questacosa era veicolato da un lock, il quale diventava un collo di bottiglia in caso di un elevatolavoroparallelo.Per questomotivonellaversione 4.0 è statautilizzatauna lock-free collection chepermette di scalaremeglio. DEMO - ThreadPoolMaxActiveThreadPRATICA - CPUBoundAPMPRATICA - CPUBoundTAP
  2. Quandousiamoi Task ilfunzionamentodiventa un po’ piùarticolato.Come nelcasodeiWorkItemquando un Task vieneschedulatovieneposizionatonella coda globale e prelevatodai Worker Threads.Fin qui niente di nuovo. Però se un Task in esecuzione genera altri Task, questivengonomessi in una coda locale al Worker Thread.Terminatoil Task in corsoil Worker Thread preleva un nuovo Task da processare, questavoltautilizzando un algoritmo di tipo LIFO, per motivi di ottimizzazione, perchè molto probabilmenteilnuovo Task dovràlavorare con idatiappenagenerati dal vecchio Task, quindiancorapresenti in cache.Datocheil Worker Thread è l’unico Thread in grado di accedereallatestadella coda locale in questocaso non avviene un accessoconcorrente.Quando la coda di un Worker Thread è vuotaquet’ultimoruba un Task dalla coda locale di un’altro Worker Thread utilizzando un algoritmooppostoovvero FIFO, in questocasovieneprelevato un elemento in coda e non dallatesta al fine di ridurre I conflitti e preservare la cache.Quando non ci sonopiù Tasks nelle code localii Worker Thread tornano a prelevaredalla coda globale.Da qui in poi tornatutto come prima, quindi se non c’èpiùlavoro da svolgerei Worker Threads vanno in Sleep per un certo lasso di tempo, dopo di che se continua a non essercilavorosi auto terminano.