SlideShare a Scribd company logo
1 of 84
History of asynchronous in .NET
Tour around evolution of asynchronous computing in .NET
Marcin Tyborowski
• .NET Developer at Billennium
• Speaker
• Co-organizer of Programisotk
Why should I analyze the history?
• Better understanding of concept
• See why this mechanism took its current form
async await
Agenda
• Async programming basics
• History of asynchronous in .NET
• A lot of complaints
• Some WTF’s
• What lies beneath
Async programming
writing computer programs so that events happen
outside of the main program flow, in the same
overlapping time frame.
Asynchronous models
Multiple machines
Multiple processes
Multiple threads
Thread Thread
Thread Thread
Heap memory
All of these have their place in complex
systems, and different languages, platforms,
and technologies tend to favor a particular
model
Concurrency vs parallelism
Concurrency is about dealing with lots of things at
once.
Parallelism is about doing lots of things at once.
What’s new?
• Thread
• ThreadPool
System.Threading namespace
Thread
• Simple API for dealing with thread
• 1:1 map to OS thread
• Foreground & background
• A lot of control == a lot of work
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(ThreadWork.DoWork);
thread1.Start();
}
}
public class ThreadWork
{
public static void DoWork()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Working thread...");
Thread.Sleep(100);
}
}
}
Console.WriteLine($"Current AppDomain: {Thread.GetDomain().FriendlyName}");
Console.WriteLine($"Current Context Id: {Thread.CurrentContext.ContextID}");
Console.WriteLine($"Thread name: {Thread.CurrentThread.Name}");
Console.WriteLine($"Is alive?: {Thread.CurrentThread.IsAlive}");
Console.WriteLine($"State: {Thread.CurrentThread.ThreadState}");
Console.WriteLine($"Priority: {Thread.CurrentThread.Priority}");
ThreadPool
• Linked list of work items
• Reuse created threads
• Minimalize responsibility of thread
management
class Program
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(ThreadWork.DoWorkInThreadPool);
}
}
public class ThreadWork
{
public static void DoWorkInThreadPool(object stateInfo)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Hello from threadpool...");
Thread.Sleep(100);
}
}
}
What’s wrong?
• Thread is expensive to create
• Uncontroller threads creation
can cause consuming memory
• Working with ThreadPool is still
very complex
Asynchronous Programming Model APM
• Introduced with .NET 1.1
• Simplifies working with ThreadPool
• Pair of methods and call object
static void Main(string[] args)
{
AddictionDelegate add = AddOperation;
IAsyncResult result =
add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData");
int operationResult = add.EndInvoke(result);
}
static int AddOperation(int a, int b)
{
return a + b;
}
static void AddOperationComplete(IAsyncResult ar)
{
Console.WriteLine($"Write {ar.AsyncState}");
Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}");
}
static void Main(string[] args)
{
AddictionDelegate add = AddOperation;
IAsyncResult result =
add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData");
int operationResult = add.EndInvoke(result);
}
static int AddOperation(int a, int b)
{
return a + b;
}
static void AddOperationComplete(IAsyncResult ar)
{
Console.WriteLine($"Write {ar.AsyncState}");
Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}");
}
static void Main(string[] args)
{
AddictionDelegate add = AddOperation;
IAsyncResult result =
add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData");
int operationResult = add.EndInvoke(result);
}
static int AddOperation(int a, int b)
{
return a + b;
}
static void AddOperationComplete(IAsyncResult ar)
{
Console.WriteLine($"Write {ar.AsyncState}");
Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}");
}
What’s wrong?
• APM make async code very
different from sync code
• Need to run End___ method to
clean up allocated resources
• Problems with GUI apps
• .NET Core?
What’s new?
• Synchronization Context
• Event-based Asynchronous Pattern EAP
Synchronization Context
• Unification dealing with UI thread in WinForms, WPF, Silverlight
• While initialization UI creates instance of SynchronizationContext
Deadlock?
public void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var result = SomeAsyncMethod().Result;
resultTB.Text = result;
}
public async Task<string> SomeAsyncMethod()
{
var result = await FetchDataAsync();
return result;
}
public void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var result = SomeAsyncMethod().Result;
resultTB.Text = result;
}
public async Task<string> SomeAsyncMethod()
{
var result = await FetchDataAsync();
return result;
}
public void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var result = SomeAsyncMethod().Result;
resultTB.Text = result;
}
public async Task<string> SomeAsyncMethod()
{
var result = await FetchDataAsync().ConfigureAwait(false);
return result;
}
Event-based Aysynchronous Pattern
• Each operation has
• method to start async work
• event that fires when operation is completed
• Improve error handling
• Resolve UI interaction problems
public event CalculationHandler CalculationCompleted;
private void RunCalculation(object sender, RoutedEventArgs e)
{
CalculationCompleted += OnCalculationCompleted;
CalculateSomething(10, 20, sender, new CalculatorEventArgs());
}
private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs
e)
{
e.Result = a + b;
CalculationCompleted.Invoke(sender, e);
}
private void OnCalculationCompleted(object sender, CalculatorEventArgs e)
{
ResultLabel.Text = e.Result.ToString();
CalculationCompleted -= OnCalculationCompleted;
}
public event CalculationHandler CalculationCompleted;
private void RunCalculation(object sender, RoutedEventArgs e)
{
CalculationCompleted += OnCalculationCompleted;
CalculateSomething(10, 20, sender, new CalculatorEventArgs());
}
private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs
e)
{
e.Result = a + b;
CalculationCompleted.Invoke(sender, e);
}
private void OnCalculationCompleted(object sender, CalculatorEventArgs e)
{
ResultLabel.Text = e.Result.ToString();
CalculationCompleted -= OnCalculationCompleted;
}
public event CalculationHandler CalculationCompleted;
private void RunCalculation(object sender, RoutedEventArgs e)
{
CalculationCompleted += OnCalculationCompleted;
CalculateSomething(10, 20, sender, new CalculatorEventArgs());
}
private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs
e)
{
e.Result = a + b;
CalculationCompleted.Invoke(sender, e);
}
private void OnCalculationCompleted(object sender, CalculatorEventArgs e)
{
ResultLabel.Text = e.Result.ToString();
CalculationCompleted -= OnCalculationCompleted;
}
private void RunCalculation(object sender, RoutedEventArgs e)
{
CalculationCompleted += OnCalculationCompleted;
Thread t = new Thread(() => CalculateSomething(10, 20, sender, new
CalculatorEventArgs()));
t.Start();
}
private void OnCalculationCompleted(object sender, CalculatorEventArgs e)
{
Dispatcher.Invoke(() =>
{
ResultLabel.Text = e.Result.ToString();
});
CalculationCompleted -= OnCalculationCompleted;
}
private void RunCalculation(object sender, RoutedEventArgs e)
{
CalculationCompleted += OnCalculationCompleted;
Thread t = new Thread(() => CalculateSomething(10, 20, sender, new
CalculatorEventArgs()));
t.Start();
}
private void OnCalculationCompleted(object sender, CalculatorEventArgs e)
{
Dispatcher.Invoke(() =>
{
ResultLabel.Text = e.Result.ToString();
});
CalculationCompleted -= OnCalculationCompleted;
}
Error handling
private void CalculateSomething(int a, int b, object sender,
CalculatorEventArgs e)
{
try
{
e.Result = a + b;
}
catch (Exception ex)
{
e.Error = ex.Message;
}
finally
{
CalculationCompleted.Invoke(sender, e);
}
}
private void OnCalculationCompleted(object sender,
CalculatorEventArgs e)
{
if (e.Error == null)
// Update UI
else
// Log error
CalculationCompleted -= OnCalculationCompleted;
}
What’s wrong?
• Still async code is very
different from sync code
• A lot of elements to implement
and be aware of
What’s new?
• Lambda expressions
delegate int FuncForString(string text);
// C# 1.0 delegate type and delegate instance
FuncForString fun1 = new FuncForString(GetStringLength);
delegate int FuncForString(string text);
// C# 2.0 method group conversion
FuncForString fun2 = GetStringLength;
// C# 2.0 generic delegate and anonymous method
Func<string, int> fun3 = delegate (string text)
{ return text.Length; };
// C# 3.0 lamba expression
Func<string, int> fun4 = (string text) =>
{ return text.Length; };
// C# 3.0 no need unnecessary parentheses
Func<string, int> fun7 = text => text.Length;
What’s new?
• ThreadPool queue remodelling
• Work stealing queues
• Task Parallel Libarary TPL
ThreadPool queue remodelling
Work stealing queues
Task Parallel Library
• Set of software APIs in the System.Threading.Tasks
• Task represents an asynchronous unit of work
• Easier to use for developers
Compute-based task
• Abstraction for OS thread
• Two possibilities
• Create new thread
• Schedule work on reusable ThreadPool
• Task.Run
• TaskFactory.StartNew
static void Main(string[] args)
{
Task t = new Task(Speak);
t.Start();
Console.WriteLine("Waiting for completion");
t.Wait();
Console.ReadKey();
}
private static void Speak()
{
Console.WriteLine("Hello world");
}
static void Main(string[] args)
{
Task t1 = Task.Run(Speak);
Task t2 = Task.Factory.StartNew(Speak);
Console.WriteLine("Waiting for completion");
t1.Wait();
t2.Wait();
}
private static void Speak()
{
Console.WriteLine("Hello world");
}
static void Main(string[] args)
{
var message = "Hello World";
Task t1 = Task.Run(() => SpeakWithParam(message));
Task t2 = Task.Factory.StartNew(() => SpeakWithParam(message));
Console.WriteLine("Waiting for completion");
t1.Wait();
t2.Wait();
}
private static void SpeakWithParam(string textToSpeak)
{
Console.WriteLine(textToSpeak);
}
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() => Console.WriteLine(i));
}
for (int i = 0; i < 10; i++)
{
int captureI = i;
Task.Factory.StartNew(() => Console.WriteLine(captureI));
}
I/O-based task
• Ask for external resource and do other things while waiting for
completion
static void Main(string[] args)
{
var url = "https://google.com";
Task task1 = Task.Factory.StartNew(() => DownloadWebPage(url));
// synchronous operations
task1.Wait();
Console.ReadKey();
}
private static string DownloadWebPage(string url)
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
{
return reader.ReadToEnd();
}
}
static void Main(string[] args)
{
var url = "https://google.com";
Task task1 = Task.Factory.StartNew(() => DownloadWebPage(url));
// synchronous operations
task1.Wait();
Console.ReadKey();
}
private static string DownloadWebPage(string url)
{
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
{
return reader.ReadToEnd();
}
}
Child tasks
• Parent wait for child
completion
Chained tasks
• ContinueWith
Task
Task Task Task
Task Task Task
What’s wrong?
• Code is still different
from sync code
What’s new?
• Task-based Asynchronous Pattern
• async/await
• Wait()s, Results no longer needed
static async Task<int> TestAsync()
{
Task<int> firstTask = GetNumberAsync(1);
Task<int> secondTask = GetNumberAsync(2);
Task<int> thirdTask = GetNumberAsync(4);
// some synchronous operations
var firstResult = await firstTask;
var secondResult = await secondTask;
var thirdResult = await thirdTask;
return firstResult + secondResult + thirdResult;
}
public static async Task<int> GetNumberAsync(int number)
=> await Task.Run(() => number);
static async Task<int> TestAsync()
{
Task<int> firstTask = GetNumberAsync(1);
Task<int> secondTask = GetNumberAsync(2);
Task<int> thirdTask = GetNumberAsync(4);
// some synchronous operations
var firstResult = await firstTask;
var secondResult = await secondTask;
var thirdResult = await thirdTask;
return firstResult + secondResult + thirdResult;
}
public static async Task<int> GetNumberAsync(int number)
=> await Task.Run(() => number);
[CompilerGenerated]
[StructLayout(LayoutKind.Auto)]
private struct <TestAsync>d__1 : IAsyncStateMachine
{
public int <>1__state;
public AsyncTaskMethodBuilder<int> <>t__builder;
private int <firstResult>5__2;
private int <secondResult>5__3;
private TaskAwaiter<int> <>u__1;
void IAsyncStateMachine.MoveNext()
{
int num = this.<>1__state;
int result2;
try
{
TaskAwaiter<int> awaiter;
switch (num)
{
case 1:
awaiter = this.<>u__1;
this.<>u__1 = default(TaskAwaiter<int>);
this.<>1__state = -1;
goto IL_E1;
case 2:
awaiter = this.<>u__1;
this.<>u__1 = default(TaskAwaiter<int>);
this.<>1__state = -1;
goto IL_14F;
default:
// some code
break;
}
}
IL_E1:
result = awaiter.GetResult();
this.<secondResult>5__3 = result;
Console.WriteLine(this.<secondResult>5__3);
awaiter = Program.GetNumberAsync(4).GetAwaiter();
if (!awaiter.IsCompleted)
{
this.<>1__state = 2;
this.<>u__1 = awaiter;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter<int>,
Program.<TestAsync>d__1>(ref awaiter, ref this);
return;
}
IL_14F:
int thirdResult = awaiter.GetResult();
Console.WriteLine("I'm done");
result2 = this.<firstResult>5__2 + this.<secondResult>5__3 +
thirdResult;
IL_E1:
result = awaiter.GetResult();
this.<secondResult>5__3 = result;
Console.WriteLine(this.<secondResult>5__3);
awaiter = Program.GetNumberAsync(4).GetAwaiter();
if (!awaiter.IsCompleted)
{
this.<>1__state = 2;
this.<>u__1 = awaiter;
this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter<int>,
Program.<TestAsync>d__1>(ref awaiter, ref this);
return;
}
IL_14F:
int thirdResult = awaiter.GetResult();
Console.WriteLine("I'm done");
result2 = this.<firstResult>5__2 + this.<secondResult>5__3 +
thirdResult;
Summary
• What lies underneath
• Better understanding of concepts
• 95% cases don’t apply
• What about these 5%
Summary
• What lies underneath
• Better understanding of concepts
• 95% cases don’t apply
• What about these 5%
• Avoid Wait() and
GetAwaiter().GetResult()
Links
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
https://foreverframe.net/what-lies-beneath-asyncawait-in-c/
https://github.com/tbr09/Multithreading
https://www.youtube.com/watch?v=ZvglMATXP6o
https://codingcanvas.com/history-of-asynchronous-programming-
models-in-net-framework/
https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-
programming-patterns/task-based-asynchronous-pattern-tap
Thanks for your attention 
@mtyborowski09 @tbr09mtyborowski09@gmail.com

More Related Content

What's hot

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performanceRafael Winterhalter
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
Conan a C/C++ Package Manager
Conan a C/C++ Package ManagerConan a C/C++ Package Manager
Conan a C/C++ Package ManagerUilian Ries
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesICS
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 

What's hot (20)

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performance
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Fortran induction project. DGTSV DGESV
Fortran induction project. DGTSV DGESVFortran induction project. DGTSV DGESV
Fortran induction project. DGTSV DGESV
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Java GC
Java GCJava GC
Java GC
 
Conan a C/C++ Package Manager
Conan a C/C++ Package ManagerConan a C/C++ Package Manager
Conan a C/C++ Package Manager
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Exception handling
Exception handlingException handling
Exception handling
 
Junit
JunitJunit
Junit
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 

Similar to History of asynchronous in .NET

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverMongoDB
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel ProcessingRTigger
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовYandex
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 

Similar to History of asynchronous in .NET (20)

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET Driver
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Async fun
Async funAsync fun
Async fun
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
От Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей РодионовОт Java Threads к лямбдам, Андрей Родионов
От Java Threads к лямбдам, Андрей Родионов
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

History of asynchronous in .NET

  • 1. History of asynchronous in .NET Tour around evolution of asynchronous computing in .NET
  • 2. Marcin Tyborowski • .NET Developer at Billennium • Speaker • Co-organizer of Programisotk
  • 3. Why should I analyze the history? • Better understanding of concept • See why this mechanism took its current form
  • 5. Agenda • Async programming basics • History of asynchronous in .NET • A lot of complaints • Some WTF’s • What lies beneath
  • 6. Async programming writing computer programs so that events happen outside of the main program flow, in the same overlapping time frame.
  • 11. All of these have their place in complex systems, and different languages, platforms, and technologies tend to favor a particular model
  • 13. Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.
  • 14.
  • 15.
  • 16. What’s new? • Thread • ThreadPool System.Threading namespace
  • 17. Thread • Simple API for dealing with thread • 1:1 map to OS thread • Foreground & background • A lot of control == a lot of work
  • 18. class Program { static void Main(string[] args) { Thread thread1 = new Thread(ThreadWork.DoWork); thread1.Start(); } } public class ThreadWork { public static void DoWork() { for (int i = 0; i < 3; i++) { Console.WriteLine("Working thread..."); Thread.Sleep(100); } } }
  • 19. Console.WriteLine($"Current AppDomain: {Thread.GetDomain().FriendlyName}"); Console.WriteLine($"Current Context Id: {Thread.CurrentContext.ContextID}"); Console.WriteLine($"Thread name: {Thread.CurrentThread.Name}"); Console.WriteLine($"Is alive?: {Thread.CurrentThread.IsAlive}"); Console.WriteLine($"State: {Thread.CurrentThread.ThreadState}"); Console.WriteLine($"Priority: {Thread.CurrentThread.Priority}");
  • 20. ThreadPool • Linked list of work items • Reuse created threads • Minimalize responsibility of thread management
  • 21. class Program { static void Main(string[] args) { ThreadPool.QueueUserWorkItem(ThreadWork.DoWorkInThreadPool); } } public class ThreadWork { public static void DoWorkInThreadPool(object stateInfo) { for (int i = 0; i < 3; i++) { Console.WriteLine("Hello from threadpool..."); Thread.Sleep(100); } } }
  • 22. What’s wrong? • Thread is expensive to create • Uncontroller threads creation can cause consuming memory • Working with ThreadPool is still very complex
  • 23. Asynchronous Programming Model APM • Introduced with .NET 1.1 • Simplifies working with ThreadPool • Pair of methods and call object
  • 24. static void Main(string[] args) { AddictionDelegate add = AddOperation; IAsyncResult result = add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData"); int operationResult = add.EndInvoke(result); } static int AddOperation(int a, int b) { return a + b; } static void AddOperationComplete(IAsyncResult ar) { Console.WriteLine($"Write {ar.AsyncState}"); Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}"); }
  • 25. static void Main(string[] args) { AddictionDelegate add = AddOperation; IAsyncResult result = add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData"); int operationResult = add.EndInvoke(result); } static int AddOperation(int a, int b) { return a + b; } static void AddOperationComplete(IAsyncResult ar) { Console.WriteLine($"Write {ar.AsyncState}"); Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}"); }
  • 26. static void Main(string[] args) { AddictionDelegate add = AddOperation; IAsyncResult result = add.BeginInvoke(10, 5, new AsyncCallback(AddOperationComplete), "someData"); int operationResult = add.EndInvoke(result); } static int AddOperation(int a, int b) { return a + b; } static void AddOperationComplete(IAsyncResult ar) { Console.WriteLine($"Write {ar.AsyncState}"); Console.WriteLine($"ThreadId: { Thread.CurrentThread.ManagedThreadId}"); }
  • 27. What’s wrong? • APM make async code very different from sync code • Need to run End___ method to clean up allocated resources • Problems with GUI apps • .NET Core?
  • 28.
  • 29.
  • 30. What’s new? • Synchronization Context • Event-based Asynchronous Pattern EAP
  • 31. Synchronization Context • Unification dealing with UI thread in WinForms, WPF, Silverlight • While initialization UI creates instance of SynchronizationContext
  • 33. public void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var result = SomeAsyncMethod().Result; resultTB.Text = result; } public async Task<string> SomeAsyncMethod() { var result = await FetchDataAsync(); return result; }
  • 34. public void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var result = SomeAsyncMethod().Result; resultTB.Text = result; } public async Task<string> SomeAsyncMethod() { var result = await FetchDataAsync(); return result; }
  • 35. public void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var result = SomeAsyncMethod().Result; resultTB.Text = result; } public async Task<string> SomeAsyncMethod() { var result = await FetchDataAsync().ConfigureAwait(false); return result; }
  • 36. Event-based Aysynchronous Pattern • Each operation has • method to start async work • event that fires when operation is completed • Improve error handling • Resolve UI interaction problems
  • 37. public event CalculationHandler CalculationCompleted; private void RunCalculation(object sender, RoutedEventArgs e) { CalculationCompleted += OnCalculationCompleted; CalculateSomething(10, 20, sender, new CalculatorEventArgs()); } private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs e) { e.Result = a + b; CalculationCompleted.Invoke(sender, e); } private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { ResultLabel.Text = e.Result.ToString(); CalculationCompleted -= OnCalculationCompleted; }
  • 38. public event CalculationHandler CalculationCompleted; private void RunCalculation(object sender, RoutedEventArgs e) { CalculationCompleted += OnCalculationCompleted; CalculateSomething(10, 20, sender, new CalculatorEventArgs()); } private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs e) { e.Result = a + b; CalculationCompleted.Invoke(sender, e); } private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { ResultLabel.Text = e.Result.ToString(); CalculationCompleted -= OnCalculationCompleted; }
  • 39. public event CalculationHandler CalculationCompleted; private void RunCalculation(object sender, RoutedEventArgs e) { CalculationCompleted += OnCalculationCompleted; CalculateSomething(10, 20, sender, new CalculatorEventArgs()); } private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs e) { e.Result = a + b; CalculationCompleted.Invoke(sender, e); } private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { ResultLabel.Text = e.Result.ToString(); CalculationCompleted -= OnCalculationCompleted; }
  • 40. private void RunCalculation(object sender, RoutedEventArgs e) { CalculationCompleted += OnCalculationCompleted; Thread t = new Thread(() => CalculateSomething(10, 20, sender, new CalculatorEventArgs())); t.Start(); } private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { Dispatcher.Invoke(() => { ResultLabel.Text = e.Result.ToString(); }); CalculationCompleted -= OnCalculationCompleted; }
  • 41. private void RunCalculation(object sender, RoutedEventArgs e) { CalculationCompleted += OnCalculationCompleted; Thread t = new Thread(() => CalculateSomething(10, 20, sender, new CalculatorEventArgs())); t.Start(); } private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { Dispatcher.Invoke(() => { ResultLabel.Text = e.Result.ToString(); }); CalculationCompleted -= OnCalculationCompleted; }
  • 43. private void CalculateSomething(int a, int b, object sender, CalculatorEventArgs e) { try { e.Result = a + b; } catch (Exception ex) { e.Error = ex.Message; } finally { CalculationCompleted.Invoke(sender, e); } }
  • 44. private void OnCalculationCompleted(object sender, CalculatorEventArgs e) { if (e.Error == null) // Update UI else // Log error CalculationCompleted -= OnCalculationCompleted; }
  • 45. What’s wrong? • Still async code is very different from sync code • A lot of elements to implement and be aware of
  • 46.
  • 48. delegate int FuncForString(string text); // C# 1.0 delegate type and delegate instance FuncForString fun1 = new FuncForString(GetStringLength);
  • 49. delegate int FuncForString(string text); // C# 2.0 method group conversion FuncForString fun2 = GetStringLength;
  • 50. // C# 2.0 generic delegate and anonymous method Func<string, int> fun3 = delegate (string text) { return text.Length; };
  • 51. // C# 3.0 lamba expression Func<string, int> fun4 = (string text) => { return text.Length; };
  • 52. // C# 3.0 no need unnecessary parentheses Func<string, int> fun7 = text => text.Length;
  • 53.
  • 54. What’s new? • ThreadPool queue remodelling • Work stealing queues • Task Parallel Libarary TPL
  • 57. Task Parallel Library • Set of software APIs in the System.Threading.Tasks • Task represents an asynchronous unit of work • Easier to use for developers
  • 58. Compute-based task • Abstraction for OS thread • Two possibilities • Create new thread • Schedule work on reusable ThreadPool • Task.Run • TaskFactory.StartNew
  • 59. static void Main(string[] args) { Task t = new Task(Speak); t.Start(); Console.WriteLine("Waiting for completion"); t.Wait(); Console.ReadKey(); } private static void Speak() { Console.WriteLine("Hello world"); }
  • 60. static void Main(string[] args) { Task t1 = Task.Run(Speak); Task t2 = Task.Factory.StartNew(Speak); Console.WriteLine("Waiting for completion"); t1.Wait(); t2.Wait(); } private static void Speak() { Console.WriteLine("Hello world"); }
  • 61. static void Main(string[] args) { var message = "Hello World"; Task t1 = Task.Run(() => SpeakWithParam(message)); Task t2 = Task.Factory.StartNew(() => SpeakWithParam(message)); Console.WriteLine("Waiting for completion"); t1.Wait(); t2.Wait(); } private static void SpeakWithParam(string textToSpeak) { Console.WriteLine(textToSpeak); }
  • 62. for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => Console.WriteLine(i)); }
  • 63.
  • 64. for (int i = 0; i < 10; i++) { int captureI = i; Task.Factory.StartNew(() => Console.WriteLine(captureI)); }
  • 65.
  • 66. I/O-based task • Ask for external resource and do other things while waiting for completion
  • 67. static void Main(string[] args) { var url = "https://google.com"; Task task1 = Task.Factory.StartNew(() => DownloadWebPage(url)); // synchronous operations task1.Wait(); Console.ReadKey(); } private static string DownloadWebPage(string url) { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); { return reader.ReadToEnd(); } }
  • 68. static void Main(string[] args) { var url = "https://google.com"; Task task1 = Task.Factory.StartNew(() => DownloadWebPage(url)); // synchronous operations task1.Wait(); Console.ReadKey(); } private static string DownloadWebPage(string url) { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); { return reader.ReadToEnd(); } }
  • 69. Child tasks • Parent wait for child completion Chained tasks • ContinueWith Task Task Task Task Task Task Task
  • 70. What’s wrong? • Code is still different from sync code
  • 71.
  • 72. What’s new? • Task-based Asynchronous Pattern • async/await • Wait()s, Results no longer needed
  • 73. static async Task<int> TestAsync() { Task<int> firstTask = GetNumberAsync(1); Task<int> secondTask = GetNumberAsync(2); Task<int> thirdTask = GetNumberAsync(4); // some synchronous operations var firstResult = await firstTask; var secondResult = await secondTask; var thirdResult = await thirdTask; return firstResult + secondResult + thirdResult; } public static async Task<int> GetNumberAsync(int number) => await Task.Run(() => number);
  • 74. static async Task<int> TestAsync() { Task<int> firstTask = GetNumberAsync(1); Task<int> secondTask = GetNumberAsync(2); Task<int> thirdTask = GetNumberAsync(4); // some synchronous operations var firstResult = await firstTask; var secondResult = await secondTask; var thirdResult = await thirdTask; return firstResult + secondResult + thirdResult; } public static async Task<int> GetNumberAsync(int number) => await Task.Run(() => number);
  • 75.
  • 76. [CompilerGenerated] [StructLayout(LayoutKind.Auto)] private struct <TestAsync>d__1 : IAsyncStateMachine { public int <>1__state; public AsyncTaskMethodBuilder<int> <>t__builder; private int <firstResult>5__2; private int <secondResult>5__3; private TaskAwaiter<int> <>u__1; void IAsyncStateMachine.MoveNext() { int num = this.<>1__state; int result2;
  • 77. try { TaskAwaiter<int> awaiter; switch (num) { case 1: awaiter = this.<>u__1; this.<>u__1 = default(TaskAwaiter<int>); this.<>1__state = -1; goto IL_E1; case 2: awaiter = this.<>u__1; this.<>u__1 = default(TaskAwaiter<int>); this.<>1__state = -1; goto IL_14F; default: // some code break; } }
  • 78. IL_E1: result = awaiter.GetResult(); this.<secondResult>5__3 = result; Console.WriteLine(this.<secondResult>5__3); awaiter = Program.GetNumberAsync(4).GetAwaiter(); if (!awaiter.IsCompleted) { this.<>1__state = 2; this.<>u__1 = awaiter; this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter<int>, Program.<TestAsync>d__1>(ref awaiter, ref this); return; } IL_14F: int thirdResult = awaiter.GetResult(); Console.WriteLine("I'm done"); result2 = this.<firstResult>5__2 + this.<secondResult>5__3 + thirdResult;
  • 79. IL_E1: result = awaiter.GetResult(); this.<secondResult>5__3 = result; Console.WriteLine(this.<secondResult>5__3); awaiter = Program.GetNumberAsync(4).GetAwaiter(); if (!awaiter.IsCompleted) { this.<>1__state = 2; this.<>u__1 = awaiter; this.<>t__builder.AwaitUnsafeOnCompleted<TaskAwaiter<int>, Program.<TestAsync>d__1>(ref awaiter, ref this); return; } IL_14F: int thirdResult = awaiter.GetResult(); Console.WriteLine("I'm done"); result2 = this.<firstResult>5__2 + this.<secondResult>5__3 + thirdResult;
  • 80. Summary • What lies underneath • Better understanding of concepts • 95% cases don’t apply • What about these 5%
  • 81. Summary • What lies underneath • Better understanding of concepts • 95% cases don’t apply • What about these 5% • Avoid Wait() and GetAwaiter().GetResult()
  • 82.
  • 84. Thanks for your attention  @mtyborowski09 @tbr09mtyborowski09@gmail.com

Editor's Notes

  1. Share access to processing cores but dont share memory
  2. 13 February 2002 – release of .NET 1.0
  3. WinForms – BeginInvoke in Controll class WPF, Silverlight – dispatchers
  4. Task.Run TaskFactory.StartNew – we can specify scheduler
  5. ThreadPool
  6. Kompilator wrzuca lokalna zmienna i do obiektu w stercie zeby mozna bylo sie do niego odwolac. Pytanie kiedy tworzy ten obiekt? i jest deklarowane poza ciałem pętli tak więc obiekt jest tworzony również poza ciałem pętli. Kazdy task dzieli ten obiekt. Pierwszy task zakonczy petle a reszta tasków poprostu wyświetli 10.
  7. Kompilator wrzuca lokalna zmienna i do obiektu w stercie. i jest deklarowane poza ciałem Kazdy task dzieli ten obiekt. Pierwszy task zakonczy petle a reszta tasków poprostu wyświetli 10.