SlideShare a Scribd company logo
1 of 57
http://www.slideshare.net/martenrange/
Mårten Rånge 
Ericsson AB 
@marten_range
Concurrency 
Examples for .NET
Responsive
Performance 
Scalable algorithms
Three pillars of Concurrency 
 Scalability (CPU) 
 Parallel.For 
 Responsiveness 
 Task 
 async/await 
 Consistency 
 lock 
 Interlocked.* 
 Mutex/Event/Semaphore 
 Monitor
Responsiveness
string ReadSomeText (string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = sr.ReadToEnd (); 
return result; 
} 
} 
// Blocks the thread until IO completes 
var text = ReadSomeText ("SomeText.txt");
Asyncronous programming allows 
programs to be responsive
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
}
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
}
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
}
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var first = await sr.ReadLineAsync(); 
var second = await sr.ReadLineAsync(); 
var third = await sr.ReadLineAsync(); 
return first + second + third; 
} 
}
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
} 
// Is this code correct? 
var readTask = ReadSomeTextAsync ("SomeText.txt"); 
var text = readTask.Result;
It depends
// Is this code correct (ignore exceptions)? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
++m_readingFiles; 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
--m_readingFiles; 
return result; 
} 
}
It depends
// Does both TraceTheadId() trace the same id? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
TraceThreadId (); 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
TraceThreadId (); 
return result; 
} 
}
It depends
What’s going on?
Your new ”best” friends 
 SynchronizationContext 
 Console apps 
 Continues on ThreadPool thread 
 WindowsFormsSynchronizationContext 
 Used by WindowsForms apps 
 Continues on the ”UI” thread 
 DispatcherSynchronizationContext 
 Used by WPF and ASP.NET apps 
 Continues on the ”same” thread
SynchronizationContext
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
} 
// Is this code correct? 
var readTask = ReadSomeTextAsync ("SomeText.txt"); 
var text = readTask.Result;
Yes
// Is this code correct (ignore exceptions)? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
++m_readingFiles; 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
--m_readingFiles; 
return result; 
} 
}
No
// Does both TraceTheadId() trace the same id? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
TraceThreadId (); 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
TraceThreadId (); 
return result; 
} 
}
No
DispatcherSynchronizationContext 
& 
WindowsFormsSynchronizationContext
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
return result; 
} 
} 
// Is this code correct? 
var readTask = ReadSomeTextAsync ("SomeText.txt"); 
var text = readTask.Result;
No
// Is this code correct (ignore exceptions)? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
++m_readingFiles; 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
--m_readingFiles; 
return result; 
} 
}
Yes
// Does both TraceTheadId() trace the same id? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
TraceThreadId (); 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync(); 
TraceThreadId (); 
return result; 
} 
}
Yes
So…
SynchronizationContext 
 Is ”invisible” 
 Is a thread-global state 
 Impacts the behavior of your code significantly 
 As an application developer you can make assumptions 
 As a library developer you can’t make assumptions
ConfigureAwait
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync() 
.ConfigureAwait (false); 
return result; 
} 
} 
// Is this code correct? 
var readTask = ReadSomeTextAsync ("SomeText.txt"); 
var text = readTask.Result;
Yes
// Is this code correct (ignore exceptions)? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
++m_readingFiles; 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync() 
.ConfigureAwait (false); 
--m_readingFiles; 
return result; 
} 
}
No
// Does both TraceTheadId() trace the same id? 
async Task<string> ReadSomeTextAsync(string fileName) 
{ 
TraceThreadId (); 
using (var sr = new StreamReader(fileName)) 
{ 
var result = await sr.ReadToEndAsync() 
.ConfigureAwait (false); 
TraceThreadId (); 
return result; 
} 
}
No
async/await tries to be what we want
async/await reminds me of…
What we need 
 Do one thing 
 Responsiveness 
 Predictable semantics 
 Continuation is executed by a thread-pool thread 
 Visibility 
 Thread-switching should be visible in code
F# async 
// Focuses on responsiveness 
let gameLoop = 
async { 
// Switching to new thread is explicit 
do! Async.SwitchToNewThread () 
while true do 
// let! is like await in C# 
let! messages = fromVisual.AsyncDequeue 1000 
for message in messages do 
processMessage message 
}
C# 
 yield 
 Special support for enumerators 
 LINQ 
 Special support for SQL-like syntax 
 async/await 
 Special support for asynchronous programming
F# 
 seq { for x in 0..10 -> i } 
 Enumerators implemented using Computation Expressions 
 query { for c in db.Customers do select c } 
 SQL-like syntax implemented using Computation Expressions 
 async { let! r=fromVisual.AsyncDequeue 1000 in r } 
 Asynchronous programming using Computation Expressions
Computation Expressions
With async/await always consider the…
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext 
SynchronizationContext
Mårten Rånge 
Ericsson AB 
@marten_range
Links 
 Presentation 
 http://www.slideshare.net/martenrange/ 
 Code 
 https://github.com/mrange/presentations/ 
 DIY asynchronous workflows in F# 
 http://mrange.wordpress.com/2014/06/12/diy-asynchronous-workflows- 
in-f/ 
 Asynchronous programming with async/await 
 http://msdn.microsoft.com/en-us/library/hh191443.aspx

More Related Content

What's hot

Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyErsin Er
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 

What's hot (6)

Network programming1
Network programming1Network programming1
Network programming1
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Tcpsockets
TcpsocketsTcpsockets
Tcpsockets
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
AMC Minor Technical Issues
AMC Minor Technical IssuesAMC Minor Technical Issues
AMC Minor Technical Issues
 

Similar to Concurrency Examples for .NET

Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...apidays
 
[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipeline[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipelineYusuke Kita
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Why async matters
Why async mattersWhy async matters
Why async matterstimbc
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkHendy Irawan
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Vapor – Swift is not only for iOS anymore
Vapor – Swift is not only for iOS anymoreVapor – Swift is not only for iOS anymore
Vapor – Swift is not only for iOS anymoreMilan Vít
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programmingFulvio Corno
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the ServerDoug Jones
 
Programming Languages Implementation and Design. .docx
  Programming Languages Implementation and Design. .docx  Programming Languages Implementation and Design. .docx
Programming Languages Implementation and Design. .docxaryan532920
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_iNico Ludwig
 

Similar to Concurrency Examples for .NET (20)

Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
 
15. text files
15. text files15. text files
15. text files
 
[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipeline[Deprecated] Integrating libSyntax into the compiler pipeline
[Deprecated] Integrating libSyntax into the compiler pipeline
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Why async matters
Why async mattersWhy async matters
Why async matters
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Twitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian NetworkTwitter Author Prediction from Tweets using Bayesian Network
Twitter Author Prediction from Tweets using Bayesian Network
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Vapor – Swift is not only for iOS anymore
Vapor – Swift is not only for iOS anymoreVapor – Swift is not only for iOS anymore
Vapor – Swift is not only for iOS anymore
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
Programming Languages Implementation and Design. .docx
  Programming Languages Implementation and Design. .docx  Programming Languages Implementation and Design. .docx
Programming Languages Implementation and Design. .docx
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 

More from Mårten Rånge

Know your FOSS obligations
Know your FOSS obligationsKnow your FOSS obligations
Know your FOSS obligationsMårten Rånge
 
Ray Marching Explained
Ray Marching ExplainedRay Marching Explained
Ray Marching ExplainedMårten Rånge
 
Better performance through Superscalarity
Better performance through SuperscalarityBetter performance through Superscalarity
Better performance through SuperscalarityMårten Rånge
 
Monad - a functional design pattern
Monad - a functional design patternMonad - a functional design pattern
Monad - a functional design patternMårten Rånge
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogrammingMårten Rånge
 
Concurrency scalability
Concurrency scalabilityConcurrency scalability
Concurrency scalabilityMårten Rånge
 

More from Mårten Rånge (10)

Know your FOSS obligations
Know your FOSS obligationsKnow your FOSS obligations
Know your FOSS obligations
 
Ray Marching Explained
Ray Marching ExplainedRay Marching Explained
Ray Marching Explained
 
Better performance through Superscalarity
Better performance through SuperscalarityBetter performance through Superscalarity
Better performance through Superscalarity
 
Property Based Tesing
Property Based TesingProperty Based Tesing
Property Based Tesing
 
Monad - a functional design pattern
Monad - a functional design patternMonad - a functional design pattern
Monad - a functional design pattern
 
Formlets
FormletsFormlets
Formlets
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
Meta Programming
Meta ProgrammingMeta Programming
Meta Programming
 
Concurrency scalability
Concurrency scalabilityConcurrency scalability
Concurrency scalability
 
Concurrency
ConcurrencyConcurrency
Concurrency
 

Recently uploaded

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 

Recently uploaded (20)

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 

Concurrency Examples for .NET

  • 2. Mårten Rånge Ericsson AB @marten_range
  • 4.
  • 7. Three pillars of Concurrency  Scalability (CPU)  Parallel.For  Responsiveness  Task  async/await  Consistency  lock  Interlocked.*  Mutex/Event/Semaphore  Monitor
  • 9.
  • 10. string ReadSomeText (string fileName) { using (var sr = new StreamReader(fileName)) { var result = sr.ReadToEnd (); return result; } } // Blocks the thread until IO completes var text = ReadSomeText ("SomeText.txt");
  • 11. Asyncronous programming allows programs to be responsive
  • 12. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } }
  • 13. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } }
  • 14. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } }
  • 15. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var first = await sr.ReadLineAsync(); var second = await sr.ReadLineAsync(); var third = await sr.ReadLineAsync(); return first + second + third; } }
  • 16. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } } // Is this code correct? var readTask = ReadSomeTextAsync ("SomeText.txt"); var text = readTask.Result;
  • 18. // Is this code correct (ignore exceptions)? async Task<string> ReadSomeTextAsync(string fileName) { ++m_readingFiles; using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); --m_readingFiles; return result; } }
  • 20. // Does both TraceTheadId() trace the same id? async Task<string> ReadSomeTextAsync(string fileName) { TraceThreadId (); using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); TraceThreadId (); return result; } }
  • 23. Your new ”best” friends  SynchronizationContext  Console apps  Continues on ThreadPool thread  WindowsFormsSynchronizationContext  Used by WindowsForms apps  Continues on the ”UI” thread  DispatcherSynchronizationContext  Used by WPF and ASP.NET apps  Continues on the ”same” thread
  • 25. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } } // Is this code correct? var readTask = ReadSomeTextAsync ("SomeText.txt"); var text = readTask.Result;
  • 26. Yes
  • 27. // Is this code correct (ignore exceptions)? async Task<string> ReadSomeTextAsync(string fileName) { ++m_readingFiles; using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); --m_readingFiles; return result; } }
  • 28. No
  • 29. // Does both TraceTheadId() trace the same id? async Task<string> ReadSomeTextAsync(string fileName) { TraceThreadId (); using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); TraceThreadId (); return result; } }
  • 30. No
  • 32. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); return result; } } // Is this code correct? var readTask = ReadSomeTextAsync ("SomeText.txt"); var text = readTask.Result;
  • 33. No
  • 34. // Is this code correct (ignore exceptions)? async Task<string> ReadSomeTextAsync(string fileName) { ++m_readingFiles; using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); --m_readingFiles; return result; } }
  • 35. Yes
  • 36. // Does both TraceTheadId() trace the same id? async Task<string> ReadSomeTextAsync(string fileName) { TraceThreadId (); using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync(); TraceThreadId (); return result; } }
  • 37. Yes
  • 38. So…
  • 39. SynchronizationContext  Is ”invisible”  Is a thread-global state  Impacts the behavior of your code significantly  As an application developer you can make assumptions  As a library developer you can’t make assumptions
  • 41. async Task<string> ReadSomeTextAsync(string fileName) { using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync() .ConfigureAwait (false); return result; } } // Is this code correct? var readTask = ReadSomeTextAsync ("SomeText.txt"); var text = readTask.Result;
  • 42. Yes
  • 43. // Is this code correct (ignore exceptions)? async Task<string> ReadSomeTextAsync(string fileName) { ++m_readingFiles; using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync() .ConfigureAwait (false); --m_readingFiles; return result; } }
  • 44. No
  • 45. // Does both TraceTheadId() trace the same id? async Task<string> ReadSomeTextAsync(string fileName) { TraceThreadId (); using (var sr = new StreamReader(fileName)) { var result = await sr.ReadToEndAsync() .ConfigureAwait (false); TraceThreadId (); return result; } }
  • 46. No
  • 47. async/await tries to be what we want
  • 49. What we need  Do one thing  Responsiveness  Predictable semantics  Continuation is executed by a thread-pool thread  Visibility  Thread-switching should be visible in code
  • 50. F# async // Focuses on responsiveness let gameLoop = async { // Switching to new thread is explicit do! Async.SwitchToNewThread () while true do // let! is like await in C# let! messages = fromVisual.AsyncDequeue 1000 for message in messages do processMessage message }
  • 51. C#  yield  Special support for enumerators  LINQ  Special support for SQL-like syntax  async/await  Special support for asynchronous programming
  • 52. F#  seq { for x in 0..10 -> i }  Enumerators implemented using Computation Expressions  query { for c in db.Customers do select c }  SQL-like syntax implemented using Computation Expressions  async { let! r=fromVisual.AsyncDequeue 1000 in r }  Asynchronous programming using Computation Expressions
  • 54. With async/await always consider the…
  • 55. SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext
  • 56. Mårten Rånge Ericsson AB @marten_range
  • 57. Links  Presentation  http://www.slideshare.net/martenrange/  Code  https://github.com/mrange/presentations/  DIY asynchronous workflows in F#  http://mrange.wordpress.com/2014/06/12/diy-asynchronous-workflows- in-f/  Asynchronous programming with async/await  http://msdn.microsoft.com/en-us/library/hh191443.aspx