SlideShare una empresa de Scribd logo
1 de 30
Multithreading & Async programming in .Net
(Controversial topics and common mistakes)
Vladimir Kramar
1. What is a thread itself?
2. How to create a new thread?
3. Async - Why & Where?
4. Async & locking.
5. Exceptions in async methods.
6. Tricks & Hints.
7. Closing thoughts.
Agenda
What is a thread itself?
How to create a new thread?
• Thread
• ThreadPool
• System.Threading.Timer
• APM - IAsyncResult, BeginInvoke(), EndInvoke()
• EAP - BackgroundWorker
• TAP - Task and Async / Await approach
.Net 1.x
.Net 2.0
.Net 4.x
System.Threading.Thread
We should not use this class unless:
 We need to set a stack size, apartment state or culture for a new thread.
 We need immediately execute a new thread.
 We need a task running in foreground mode.
 We need a thread to have a particular priority.
 We have a task that might run a long time.
Why not ThreadPool?
ThreadPool can be used something like this:
• Messy! Is not it?
• What if we have to wait for many threads to complete?
• How do we capture the return values from multiple threads?
• How do we return the control back to GUI threads?
System.Threading.Timer
No – Thread.Sleep() Yes – To using of Timer
Asynchronous Patterns
• APM Asynchronous Programming
Model (IAsyncResult)
• EAP Event-based Asynchronous Pattern
(BackgroundWorker)
• TAP Task-based Asynchronous Pattern
(Task & async / await)
IAsyncResult
(with callback)
IAsyncResult – with callback Async / Await – with void method
IAsyncResult – without callback Async / Await – with Task async method
IAsyncResult
(without callback)
Why Async / Await is better?
• Implementing of one method instead of two.
• More readable implementation.
• Copying the thread context.
• Ability to track async operations progress.
• Ability to create cold async operations.
How to create a new thread?
• TAP - Task and Async / Await approach
• Thread
• ThreadPool
• System.Threading.Timer
• APM - IAsyncResult, BeginInvoke(), EndInvoke()
• EAP - BackgroundWorker
In most cases:
In some special cases:
Do not use it:
Async – Why & Where?
Async – Why & Where?
Difference between Multithreading and Asynchronous programming:
Multithreading: Async (better approach):
Async – Why & Where?
Difference between Multithreading and Asynchronous programming:
Better just to execute it with a new thread:
General methods can not be executed
as asynchronous even if we use async / await:
Async – Why & Where?
Async – Why & Where?
Why? – To increase scalability.
Where? – Whenever it is possible for long-running operations.
Under a hood of Async / Await.
Let’s look at this async method: Behind the scene it performs the following:
• Copying all local variable values.
• Copying ‘this’ object state.
• Tracking some other state data like a current stack pointer,
await number, etc.
• Remembering Synchronization and other thread contexts.
• Then restoring all these data in callback threads.
• And then the GarbageCollector should clean all taken
memory.
Async & Locking
Locking with Async / Await
We could use Mutex or Semaphore for locking like this:
Locking with Async / Await
Only the SemaphoreSlim supports an async lock for now:
Exceptions in async methods
Exceptions in async void
We should not implement async void methods
due to we never can catch their exceptions.
Handling exceptions in async
And then we can log this way:Just one extension method:
Tricks & Hints
Thread contexts
SynchronizationContext
ExecutionContext
SecurityContext
CallContext, LogicalCallContext
Discarding the contexts
We can prevent copying of thread context data:
In async / await methods: For new threads:
Thread stack size
IIS: In Windows Server 2008 and higher, the maximum stack size of a thread running on 32-
bit version of IIS is 256 KB, and on an x64 server is 512 KB.
Before, the max stack size of a thread in IIS equalled to 1 MB.
Diminishing of a stack size can increase scalability and consequently performance of an application.
For changing a stack size in Windows OS we can use editbin cmd utility like this:
Viewing a stack size
The fragment of an output:
To get information about stack size of your app, you can use dumpbin cmd utility:
dumpbin /headers MyApp.exe > info.txt
The 400000 is size in heximal value.
So in decimal it equals to 4194304 bytes or 4 Mb
Closing Thoughts

Más contenido relacionado

La actualidad más candente

Weaviate and Pinecone Comparison.pdf
Weaviate and Pinecone Comparison.pdfWeaviate and Pinecone Comparison.pdf
Weaviate and Pinecone Comparison.pdf
Evgenios Skitsanos
 

La actualidad más candente (20)

A brief study on Kubernetes and its components
A brief study on Kubernetes and its componentsA brief study on Kubernetes and its components
A brief study on Kubernetes and its components
 
OAuthのHolder of Key Token
OAuthのHolder of Key TokenOAuthのHolder of Key Token
OAuthのHolder of Key Token
 
Verifiable credentials explained by CCI
Verifiable credentials explained by CCIVerifiable credentials explained by CCI
Verifiable credentials explained by CCI
 
OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)
 
Kubernetes Architecture and Introduction
Kubernetes Architecture and IntroductionKubernetes Architecture and Introduction
Kubernetes Architecture and Introduction
 
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
 
Delivering: from Kafka to WebSockets | Adam Warski, SoftwareMill
Delivering: from Kafka to WebSockets | Adam Warski, SoftwareMillDelivering: from Kafka to WebSockets | Adam Warski, SoftwareMill
Delivering: from Kafka to WebSockets | Adam Warski, SoftwareMill
 
User authentication and authorizarion in Kubernetes
User authentication and authorizarion in KubernetesUser authentication and authorizarion in Kubernetes
User authentication and authorizarion in Kubernetes
 
[台灣人工智慧學校] 人工智慧民主化在台灣
[台灣人工智慧學校] 人工智慧民主化在台灣[台灣人工智慧學校] 人工智慧民主化在台灣
[台灣人工智慧學校] 人工智慧民主化在台灣
 
Présentation docker et kubernetes
Présentation docker et kubernetesPrésentation docker et kubernetes
Présentation docker et kubernetes
 
Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019Terraform Best Practices - DevOps Unicorns 2019
Terraform Best Practices - DevOps Unicorns 2019
 
Weaviate and Pinecone Comparison.pdf
Weaviate and Pinecone Comparison.pdfWeaviate and Pinecone Comparison.pdf
Weaviate and Pinecone Comparison.pdf
 
Saturn 2018: Managing data consistency in a microservice architecture using S...
Saturn 2018: Managing data consistency in a microservice architecture using S...Saturn 2018: Managing data consistency in a microservice architecture using S...
Saturn 2018: Managing data consistency in a microservice architecture using S...
 
Best Practices with Azure Kubernetes Services
Best Practices with Azure Kubernetes ServicesBest Practices with Azure Kubernetes Services
Best Practices with Azure Kubernetes Services
 
Oracle Database Appliance X5-2 アップデート内容のご紹介
Oracle Database Appliance X5-2 アップデート内容のご紹介Oracle Database Appliance X5-2 アップデート内容のご紹介
Oracle Database Appliance X5-2 アップデート内容のご紹介
 
OpenID for SSI
OpenID for SSIOpenID for SSI
OpenID for SSI
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
 
Microservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | EdurekaMicroservices Design Patterns Explained | Edureka
Microservices Design Patterns Explained | Edureka
 
Windowsコンテナ入門
Windowsコンテナ入門Windowsコンテナ入門
Windowsコンテナ入門
 
Introduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang NguyenIntroduction of Kubernetes - Trang Nguyen
Introduction of Kubernetes - Trang Nguyen
 

Similar a .NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET

“Using C#/.NET – “Controversial Topics & Common Mistakes”
“Using C#/.NET – “Controversial Topics & Common Mistakes”“Using C#/.NET – “Controversial Topics & Common Mistakes”
“Using C#/.NET – “Controversial Topics & Common Mistakes”
IT Weekend
 
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 a .NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET (20)

Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Asynchronous Programming.pptx
Asynchronous Programming.pptxAsynchronous Programming.pptx
Asynchronous Programming.pptx
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
“Using C#/.NET – “Controversial Topics & Common Mistakes”
“Using C#/.NET – “Controversial Topics & Common Mistakes”“Using C#/.NET – “Controversial Topics & Common Mistakes”
“Using C#/.NET – “Controversial Topics & Common Mistakes”
 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Multithreading and Actors
Multithreading and ActorsMultithreading and Actors
Multithreading and Actors
 
Achieving mass scale with Quasar Fibers
Achieving mass scale with Quasar FibersAchieving mass scale with Quasar Fibers
Achieving mass scale with Quasar Fibers
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
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 Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5Parallel and Distributed Computing Chapter 5
Parallel and Distributed Computing Chapter 5
 
Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017Sanger OpenStack presentation March 2017
Sanger OpenStack presentation March 2017
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
Aspect j introduction for non-programmers
Aspect j introduction for non-programmersAspect j introduction for non-programmers
Aspect j introduction for non-programmers
 
12. Parallel Algorithms.pptx
12. Parallel Algorithms.pptx12. Parallel Algorithms.pptx
12. Parallel Algorithms.pptx
 
lec5 - The processor.pptx
lec5 - The processor.pptxlec5 - The processor.pptx
lec5 - The processor.pptx
 

Más de NETFest

Más de NETFest (20)

.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
 
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE....NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
 
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
 
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
 
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem....NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
 
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A....NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
 
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
 
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос....NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
 
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive.NET Fest 2019. Roberto Freato. Azure App Service deep dive
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
 
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
 
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com....NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
 
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real....NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
 
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
 
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ....NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
 
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali....NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
 
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
 
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur....NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

.NET Fest 2018. Владимир Крамар. Многопоточное и асинхронное программирование в .NET

  • 1. Multithreading & Async programming in .Net (Controversial topics and common mistakes) Vladimir Kramar
  • 2. 1. What is a thread itself? 2. How to create a new thread? 3. Async - Why & Where? 4. Async & locking. 5. Exceptions in async methods. 6. Tricks & Hints. 7. Closing thoughts. Agenda
  • 3. What is a thread itself?
  • 4. How to create a new thread? • Thread • ThreadPool • System.Threading.Timer • APM - IAsyncResult, BeginInvoke(), EndInvoke() • EAP - BackgroundWorker • TAP - Task and Async / Await approach .Net 1.x .Net 2.0 .Net 4.x
  • 5. System.Threading.Thread We should not use this class unless:  We need to set a stack size, apartment state or culture for a new thread.  We need immediately execute a new thread.  We need a task running in foreground mode.  We need a thread to have a particular priority.  We have a task that might run a long time.
  • 6. Why not ThreadPool? ThreadPool can be used something like this: • Messy! Is not it? • What if we have to wait for many threads to complete? • How do we capture the return values from multiple threads? • How do we return the control back to GUI threads?
  • 8. Asynchronous Patterns • APM Asynchronous Programming Model (IAsyncResult) • EAP Event-based Asynchronous Pattern (BackgroundWorker) • TAP Task-based Asynchronous Pattern (Task & async / await)
  • 9. IAsyncResult (with callback) IAsyncResult – with callback Async / Await – with void method
  • 10. IAsyncResult – without callback Async / Await – with Task async method IAsyncResult (without callback)
  • 11. Why Async / Await is better? • Implementing of one method instead of two. • More readable implementation. • Copying the thread context. • Ability to track async operations progress. • Ability to create cold async operations.
  • 12. How to create a new thread? • TAP - Task and Async / Await approach • Thread • ThreadPool • System.Threading.Timer • APM - IAsyncResult, BeginInvoke(), EndInvoke() • EAP - BackgroundWorker In most cases: In some special cases: Do not use it:
  • 13. Async – Why & Where?
  • 14. Async – Why & Where? Difference between Multithreading and Asynchronous programming: Multithreading: Async (better approach):
  • 15. Async – Why & Where? Difference between Multithreading and Asynchronous programming: Better just to execute it with a new thread: General methods can not be executed as asynchronous even if we use async / await:
  • 16. Async – Why & Where?
  • 17. Async – Why & Where? Why? – To increase scalability. Where? – Whenever it is possible for long-running operations.
  • 18. Under a hood of Async / Await. Let’s look at this async method: Behind the scene it performs the following: • Copying all local variable values. • Copying ‘this’ object state. • Tracking some other state data like a current stack pointer, await number, etc. • Remembering Synchronization and other thread contexts. • Then restoring all these data in callback threads. • And then the GarbageCollector should clean all taken memory.
  • 20. Locking with Async / Await We could use Mutex or Semaphore for locking like this:
  • 21. Locking with Async / Await Only the SemaphoreSlim supports an async lock for now:
  • 23. Exceptions in async void We should not implement async void methods due to we never can catch their exceptions.
  • 24. Handling exceptions in async And then we can log this way:Just one extension method:
  • 27. Discarding the contexts We can prevent copying of thread context data: In async / await methods: For new threads:
  • 28. Thread stack size IIS: In Windows Server 2008 and higher, the maximum stack size of a thread running on 32- bit version of IIS is 256 KB, and on an x64 server is 512 KB. Before, the max stack size of a thread in IIS equalled to 1 MB. Diminishing of a stack size can increase scalability and consequently performance of an application. For changing a stack size in Windows OS we can use editbin cmd utility like this:
  • 29. Viewing a stack size The fragment of an output: To get information about stack size of your app, you can use dumpbin cmd utility: dumpbin /headers MyApp.exe > info.txt The 400000 is size in heximal value. So in decimal it equals to 4194304 bytes or 4 Mb