SlideShare a Scribd company logo
http://www.slideshare.net/martenrange/
Mårten Rånge 
Ericsson AB 
@marten_range
Concurrency 
Examples for .NET
Concurrency - responsiveness in .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
Concurrency - responsiveness in .NET
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 (6)

PPT
Network programming1
Soham Sengupta
 
PPTX
Compiler Design
sweetysweety8
 
PDF
Tcpsockets
mcjayaprasanna8
 
PDF
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
DOCX
692015 programming assignment 1 building a multi­threaded w
smile790243
 
PPTX
AMC Minor Technical Issues
Apache Traffic Server
 
Network programming1
Soham Sengupta
 
Compiler Design
sweetysweety8
 
Tcpsockets
mcjayaprasanna8
 
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
692015 programming assignment 1 building a multi­threaded w
smile790243
 
AMC Minor Technical Issues
Apache Traffic Server
 

Similar to Concurrency - responsiveness in .NET (20)

PDF
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
PPTX
History of asynchronous in .NET
Marcin Tyborowski
 
PPTX
Async Programming in C# 5
Pratik Khasnabis
 
PPSX
Async-await best practices in 10 minutes
Paulo Morgado
 
PPTX
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
PDF
Async await...oh wait!
Thomas Pierrain
 
PPTX
C# 5 deep drive into asynchronous programming
Praveen Prajapati
 
PPTX
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Karel Zikmund
 
PDF
Async Await for Mobile Apps
Craig Dunn
 
PPTX
Ddd melbourne 2011 C# async ctp
Pratik Khasnabis
 
PDF
Deep Dive async/await in Unity with UniTask(EN)
Yoshifumi Kawai
 
PDF
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
PPTX
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Karel Zikmund
 
PPTX
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 
PDF
Concurrecny inf sharp
Riccardo Terrell
 
PPTX
Task parallel library presentation
ahmed sayed
 
PDF
Why async matters
timbc
 
DOCX
Asynchronyin net
Soacat Blogspot
 
PPTX
Async await
Jeff Hart
 
PPTX
Async/Await
Jeff Hart
 
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
History of asynchronous in .NET
Marcin Tyborowski
 
Async Programming in C# 5
Pratik Khasnabis
 
Async-await best practices in 10 minutes
Paulo Morgado
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Async await...oh wait!
Thomas Pierrain
 
C# 5 deep drive into asynchronous programming
Praveen Prajapati
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
Karel Zikmund
 
Async Await for Mobile Apps
Craig Dunn
 
Ddd melbourne 2011 C# async ctp
Pratik Khasnabis
 
Deep Dive async/await in Unity with UniTask(EN)
Yoshifumi Kawai
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Karel Zikmund
 
Async CTP 3 Presentation for MUGH 2012
Sri Kanth
 
Concurrecny inf sharp
Riccardo Terrell
 
Task parallel library presentation
ahmed sayed
 
Why async matters
timbc
 
Asynchronyin net
Soacat Blogspot
 
Async await
Jeff Hart
 
Async/Await
Jeff Hart
 
Ad

More from Mårten Rånge (10)

PPTX
Know your FOSS obligations
Mårten Rånge
 
PPTX
Ray Marching Explained
Mårten Rånge
 
PPTX
Better performance through Superscalarity
Mårten Rånge
 
PPTX
Property Based Tesing
Mårten Rånge
 
PPTX
Monad - a functional design pattern
Mårten Rånge
 
PPTX
Formlets
Mårten Rånge
 
PPTX
Pragmatic metaprogramming
Mårten Rånge
 
PPTX
Meta Programming
Mårten Rånge
 
PPTX
Concurrency scalability
Mårten Rånge
 
PPTX
Concurrency
Mårten Rånge
 
Know your FOSS obligations
Mårten Rånge
 
Ray Marching Explained
Mårten Rånge
 
Better performance through Superscalarity
Mårten Rånge
 
Property Based Tesing
Mårten Rånge
 
Monad - a functional design pattern
Mårten Rånge
 
Formlets
Mårten Rånge
 
Pragmatic metaprogramming
Mårten Rånge
 
Meta Programming
Mårten Rånge
 
Concurrency scalability
Mårten Rånge
 
Concurrency
Mårten Rånge
 
Ad

Recently uploaded (20)

PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 

Concurrency - responsiveness in .NET

  • 2. Mårten Rånge Ericsson AB @marten_range
  • 7. Three pillars of Concurrency  Scalability (CPU)  Parallel.For  Responsiveness  Task  async/await  Consistency  lock  Interlocked.*  Mutex/Event/Semaphore  Monitor
  • 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