SlideShare a Scribd company logo
Understanding
ConfigureAwait(false)
Shuhei Eda
If you’ve already read this blog, Finish reading
this slides. Do not waste your time!
Agenda
• Understanding SynchronizationContext and TaskScheduler
• How do SynchronizationContext and TaskScheduler relate to await?
• Problems of Posting callbacks
• What does ConfigureAwait(false) do?
Understanding
SynchronizationContext and
TaskScheduler
Official definition of SynchronizationContext
Official document says…
“Provides the basic functionality for propagating a synchronization
context in various synchronization models.”
Too abstract!!!
Easier explanation of SynchronizationContext
• Provides Post method which passes a
delegate(callback, action..) from one
thread to another
• Base method just enqueues a callback
into ThreadPool
Current
Thread
ThreadPool
Thread
Post
Sample code of SynchronizationContext
Output
ThreadId: 1
Action Called
ThreadId: 11
Derived-Type of SynchronizationContext
• Some frameworks have a specific thread
• E.X. Winforms sets Derived-Type of
SynchronizationContext to allow the context to be
brought onto the UI thread.
• The callback is invoked on UI thread
Current
Thread
UI Thread
Post
(BeginInvoke)
Sample code of SynchronizationContext
Output
ThreadId: 1
Action Called
ThreadId: 1
TaskScheduler
• Very Roughly Speaking: Task’s version of SynchronizationContext
• Provides “QueueTask” method which enqueues tasks to the Thread
pool.
• If the LongRunning option is true, it creates a new thread.
How do SynchronizationContext and
TaskScheduler relate to await?
Write asynchronous code
(Before .NET 4.0)
• Use TaskScheduler
• Use SynchronizationContext
Thread 1 Thread 2
ContinueWith
GetStringAsync
Post back
Write asynchronous code
(Before .NET 4.0)
• Use TaskScheduler
• Use SynchronizationContext
Thread 1 Thread 2
ContinueWith
GetStringAsync
SynchronizationContext is captured!
Post back
Write asynchronous code
(After .NET 4.5)
Can use async await keyword
ContinueWith
GetStringAsync
Post back
Thread 1 Thread 2
Detailed capturing behavior
Problems of Posting callbacks
Problems of Posting callbacks
• Deadlock
• If an original thread calls Wait(),
Result, or GetResult(), it gets
blocked until the thread running
the task finishes.
• The subsequent thread waits until
the original thread becomes
available.
• Performance
• Enqueueing the callback to
another thread is an expensive
operation
Cannot do
post back
Thread 1 Thread 2
Blocking
HeavyAsync()
.Result
Doing heavy tasks
Deadlock!
Problems of Posting callbacks
• Deadlock
• If an original thread calls Wait(),
Result, or GetResult(), it gets
blocked until the thread running
the task finishes.
• The subsequent thread waits until
the original thread becomes
available.
• Performance
• Enqueueing the callback to
another thread is an expensive
operation
Cannot do
post back
Thread 1 Thread 2
Blocking
HeavyAsync()
.Result
Doing heavy tasks
I will restart after
Thread 2’s method is
done.
Deadlock!
Problems of Posting callbacks
• Deadlock
• If an original thread calls Wait(),
Result, or GetResult(), it gets
blocked until the thread running
the task finishes.
• The subsequent thread waits until
the original thread becomes
available.
• Performance
• Enqueueing the callback to
another thread is an expensive
operation
Cannot do
post back
Thread 1 Thread 2
Blocking
HeavyAsync()
.Result
Doing heavy tasks
I will restart after
Thread 2’s method is
done.
I will do post-back when
Thread1 becomes available
Deadlock!
Sample code of deadlock
Result:
1 : Main Start
1 : ChildSampleAsync Start
This block is trying to be executed
in Thread1, but Thread 1 is
blocked, so the deadlock occurs.
Since the “Result” method is
called, Thread1 gets blocked
What does ConfigureAwait(false)
do?
ConfigureAwait(false) = Prevents capturing
SynchronizationContext
• Sample code of capturing process
• ConfigureAwait(false) bypasses the following block of code.
If ConfigureAwait(false) is called..
• It will not post the callback.
• The code block after the “await”
keyword will continue running
on the same thread.
Thread 1 Thread 2
Blocking
HeavyAsync()
.Result
Doing heavy tasks
No post happens and the
method is processed in
the same thread.
Sample code of NON-deadlock
Result:
1 : Main Start
1 : ChildSampleAsync Start
7 : ChildSampleAsync End
1 : Main End
This code block runs on another
thread, not in original thread.
ConfiureAwait(false) is called.
Advantages of calling ConfigureAwait(false)
• Avoiding deadlocks
• Performance
• Since no queueing of the callback occurs.
Guidance of using ConfigureAwait(false)
• Should use ConfigureAwait(false)
• general-purpose libraries
• ASP.NET Core
• Console App
• Should NOT use ConfigureAwait(false)
• Win Forms
• ASP.NET (HttpContext.Current might be badly affected)
• WPF
• Silverlight
Reference
• https://devblogs.microsoft.com/dotnet/configureawait-faq/

More Related Content

What's hot

오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
Amazon Web Services Korea
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control System
KMS Technology
 
Git basics for beginners
Git basics for beginnersGit basics for beginners
Git basics for beginners
PravallikaTammisetty
 
송창규, unity build로 빌드타임 반토막내기, NDC2010
송창규, unity build로 빌드타임 반토막내기, NDC2010송창규, unity build로 빌드타임 반토막내기, NDC2010
송창규, unity build로 빌드타임 반토막내기, NDC2010devCAT Studio, NEXON
 
Git with bitbucket
Git with bitbucketGit with bitbucket
Git with bitbucket
Sumin Byeon
 
Git workflows
Git workflowsGit workflows
Git workflows
Thuc Le Dong
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
Joshua Zhu
 
Janus & docker: friends or foe
Janus & docker: friends or foe Janus & docker: friends or foe
Janus & docker: friends or foe
Alessandro Amirante
 
React hooks
React hooksReact hooks
React hooks
Ramy ElBasyouni
 
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
InfraEngineer
 
Introduction to Version Control
Introduction to Version ControlIntroduction to Version Control
Introduction to Version Control
Jeremy Coates
 
Experience and Content Fragment
Experience and Content FragmentExperience and Content Fragment
Experience and Content Fragment
Heena Madan
 
svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드
Insub Lee
 
Jenkins
JenkinsJenkins
Jenkins
Roger Xia
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to git
Emanuele Olivetti
 
Git pour les (pas si) nuls
Git pour les (pas si) nulsGit pour les (pas si) nuls
Git pour les (pas si) nuls
Malk Zameth
 
Git
GitGit
Git Pull Requests
Git Pull RequestsGit Pull Requests
Git Pull Requests
Callon Campbell
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introduction
Alex Fernandez
 

What's hot (20)

오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control System
 
Git basics for beginners
Git basics for beginnersGit basics for beginners
Git basics for beginners
 
송창규, unity build로 빌드타임 반토막내기, NDC2010
송창규, unity build로 빌드타임 반토막내기, NDC2010송창규, unity build로 빌드타임 반토막내기, NDC2010
송창규, unity build로 빌드타임 반토막내기, NDC2010
 
Git with bitbucket
Git with bitbucketGit with bitbucket
Git with bitbucket
 
Git workflows
Git workflowsGit workflows
Git workflows
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
Janus & docker: friends or foe
Janus & docker: friends or foe Janus & docker: friends or foe
Janus & docker: friends or foe
 
React hooks
React hooksReact hooks
React hooks
 
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
[MeetUp][1st] 오픈소스를 활용한 xflow 수집-시각화
 
Introduction to Version Control
Introduction to Version ControlIntroduction to Version Control
Introduction to Version Control
 
Experience and Content Fragment
Experience and Content FragmentExperience and Content Fragment
Experience and Content Fragment
 
svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드svn 능력자를 위한 git 개념 가이드
svn 능력자를 위한 git 개념 가이드
 
Jenkins
JenkinsJenkins
Jenkins
 
A Practical Introduction to git
A Practical Introduction to gitA Practical Introduction to git
A Practical Introduction to git
 
Git pour les (pas si) nuls
Git pour les (pas si) nulsGit pour les (pas si) nuls
Git pour les (pas si) nuls
 
Git
GitGit
Git
 
Git Pull Requests
Git Pull RequestsGit Pull Requests
Git Pull Requests
 
Spring batch introduction
Spring batch introductionSpring batch introduction
Spring batch introduction
 

Similar to C#: Understanding ConfigureAwait(false)

Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
Deivaa
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Sachintha Gunasena
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
Parallel programming
Parallel programmingParallel programming
Parallel programming
Swain Loda
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
ramyan49
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
madan r
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
Tuan Chau
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
Iulian Dragos
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
Jeremy Likness
 
Multi Threading
Multi ThreadingMulti Threading
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
Krystian Zybała
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
Syed Zaid Irshad
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
ssuserec53e73
 
Java class 6
Java class 6Java class 6
Java class 6
Edureka!
 

Similar to C#: Understanding ConfigureAwait(false) (20)

Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
java threads
java threadsjava threads
java threads
 
Parallel programming
Parallel programmingParallel programming
Parallel programming
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Rethinking the debugger
Rethinking the debuggerRethinking the debugger
Rethinking the debugger
 
Java threading
Java threadingJava threading
Java threading
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
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
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Synchronization problem with threads
Synchronization problem with threadsSynchronization problem with threads
Synchronization problem with threads
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
Java class 6
Java class 6Java class 6
Java class 6
 

Recently uploaded

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
Madhumitha Jayaram
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
JamalHussainArman
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 

Recently uploaded (20)

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Wearable antenna for antenna applications
Wearable antenna for antenna applicationsWearable antenna for antenna applications
Wearable antenna for antenna applications
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptxML Based Model for NIDS MSc Updated Presentation.v2.pptx
ML Based Model for NIDS MSc Updated Presentation.v2.pptx
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 

C#: Understanding ConfigureAwait(false)

  • 2. If you’ve already read this blog, Finish reading this slides. Do not waste your time!
  • 3. Agenda • Understanding SynchronizationContext and TaskScheduler • How do SynchronizationContext and TaskScheduler relate to await? • Problems of Posting callbacks • What does ConfigureAwait(false) do?
  • 5. Official definition of SynchronizationContext Official document says… “Provides the basic functionality for propagating a synchronization context in various synchronization models.” Too abstract!!!
  • 6. Easier explanation of SynchronizationContext • Provides Post method which passes a delegate(callback, action..) from one thread to another • Base method just enqueues a callback into ThreadPool Current Thread ThreadPool Thread Post
  • 7. Sample code of SynchronizationContext Output ThreadId: 1 Action Called ThreadId: 11
  • 8. Derived-Type of SynchronizationContext • Some frameworks have a specific thread • E.X. Winforms sets Derived-Type of SynchronizationContext to allow the context to be brought onto the UI thread. • The callback is invoked on UI thread Current Thread UI Thread Post (BeginInvoke)
  • 9. Sample code of SynchronizationContext Output ThreadId: 1 Action Called ThreadId: 1
  • 10. TaskScheduler • Very Roughly Speaking: Task’s version of SynchronizationContext • Provides “QueueTask” method which enqueues tasks to the Thread pool. • If the LongRunning option is true, it creates a new thread.
  • 11. How do SynchronizationContext and TaskScheduler relate to await?
  • 12. Write asynchronous code (Before .NET 4.0) • Use TaskScheduler • Use SynchronizationContext Thread 1 Thread 2 ContinueWith GetStringAsync Post back
  • 13. Write asynchronous code (Before .NET 4.0) • Use TaskScheduler • Use SynchronizationContext Thread 1 Thread 2 ContinueWith GetStringAsync SynchronizationContext is captured! Post back
  • 14. Write asynchronous code (After .NET 4.5) Can use async await keyword ContinueWith GetStringAsync Post back Thread 1 Thread 2
  • 16. Problems of Posting callbacks
  • 17. Problems of Posting callbacks • Deadlock • If an original thread calls Wait(), Result, or GetResult(), it gets blocked until the thread running the task finishes. • The subsequent thread waits until the original thread becomes available. • Performance • Enqueueing the callback to another thread is an expensive operation Cannot do post back Thread 1 Thread 2 Blocking HeavyAsync() .Result Doing heavy tasks Deadlock!
  • 18. Problems of Posting callbacks • Deadlock • If an original thread calls Wait(), Result, or GetResult(), it gets blocked until the thread running the task finishes. • The subsequent thread waits until the original thread becomes available. • Performance • Enqueueing the callback to another thread is an expensive operation Cannot do post back Thread 1 Thread 2 Blocking HeavyAsync() .Result Doing heavy tasks I will restart after Thread 2’s method is done. Deadlock!
  • 19. Problems of Posting callbacks • Deadlock • If an original thread calls Wait(), Result, or GetResult(), it gets blocked until the thread running the task finishes. • The subsequent thread waits until the original thread becomes available. • Performance • Enqueueing the callback to another thread is an expensive operation Cannot do post back Thread 1 Thread 2 Blocking HeavyAsync() .Result Doing heavy tasks I will restart after Thread 2’s method is done. I will do post-back when Thread1 becomes available Deadlock!
  • 20. Sample code of deadlock Result: 1 : Main Start 1 : ChildSampleAsync Start This block is trying to be executed in Thread1, but Thread 1 is blocked, so the deadlock occurs. Since the “Result” method is called, Thread1 gets blocked
  • 22. ConfigureAwait(false) = Prevents capturing SynchronizationContext • Sample code of capturing process • ConfigureAwait(false) bypasses the following block of code.
  • 23. If ConfigureAwait(false) is called.. • It will not post the callback. • The code block after the “await” keyword will continue running on the same thread. Thread 1 Thread 2 Blocking HeavyAsync() .Result Doing heavy tasks No post happens and the method is processed in the same thread.
  • 24. Sample code of NON-deadlock Result: 1 : Main Start 1 : ChildSampleAsync Start 7 : ChildSampleAsync End 1 : Main End This code block runs on another thread, not in original thread. ConfiureAwait(false) is called.
  • 25. Advantages of calling ConfigureAwait(false) • Avoiding deadlocks • Performance • Since no queueing of the callback occurs.
  • 26. Guidance of using ConfigureAwait(false) • Should use ConfigureAwait(false) • general-purpose libraries • ASP.NET Core • Console App • Should NOT use ConfigureAwait(false) • Win Forms • ASP.NET (HttpContext.Current might be badly affected) • WPF • Silverlight