SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Besseres C#
Workshop
BASTA! Spring 2014

Rainer Stropek

Async und
Parallel

software architects gmbh

Web http://www.timecockpit.com
Mail rainer@timecockpit.com
Twitter @rstropek

Workshop
Saves the day.
Async Programming
In C# and .NET 4.5
private static void DownloadSomeTextSync()
{
using (var client = new WebClient())
{
Console.WriteLine(
client.DownloadString(new Uri(string.Format(
"http://{0}",
(Dns.GetHostAddresses("www.basta.net"))[0]))));
}
}

Synchronous
private static void DownloadSomeText()
{
var finishedEvent = new AutoResetEvent(false);
// Notice the IAsyncResult-pattern here
Dns.BeginGetHostAddresses("www.basta.net", GetHostEntryFinished,
finishedEvent);
finishedEvent.WaitOne();

}
private static void GetHostEntryFinished(IAsyncResult result)
{
var hostEntry = Dns.EndGetHostAddresses(result);
using (var client = new WebClient())
{
// Notice the Event-based asynchronous pattern here
client.DownloadStringCompleted += (s, e) =>
{
Console.WriteLine(e.Result);
((AutoResetEvent)result.AsyncState).Set();
};
client.DownloadStringAsync(new Uri(string.Format(
"http://{0}",
hostEntry[0].ToString())));
}
}

IAsyncResult
Pattern
private static void DownloadSomeText()
{
var finishedEvent = new AutoResetEvent(false);
// Notice the IAsyncResult-pattern here
Dns.BeginGetHostAddresses(
"www.basta.net",
(result) =>
{
var hostEntry = Dns.EndGetHostAddresses(result);
using (var client = new WebClient())
{
// Notice the Event-based asynchronous pattern here
client.DownloadStringCompleted += (s, e) =>
{
Console.WriteLine(e.Result);
((AutoResetEvent)result.AsyncState).Set();
};
client.DownloadStringAsync(new Uri(string.Format(
"http://{0}",
hostEntry[0].ToString())));
}
},
finishedEvent);
finishedEvent.WaitOne();
}

IAsyncResult
Pattern
With Lambdas
private static void DownloadSomeTextUsingTask()
{
Dns.GetHostAddressesAsync("www.basta.net")
.ContinueWith(t =>
{
using (var client = new WebClient())
{
return client.DownloadStringTaskAsync(
new Uri(string.Format(
"http://{0}",
t.Result[0].ToString())));
}
})
.ContinueWith(t2 => Console.WriteLine(t2.Unwrap().Result))
.Wait();
}

TPL
Notice the use of the new Task Async
Pattern APIs in .NET 4.5 here
Rules For Async Method Signatures
 Method
 Return

name ends with Async

value

Task if sync version has return type void
Task<T> if sync version has return type T

 Avoid

out and ref parameters

Use e.g. Task<Tuple<T1, T2, …>> instead
// Synchronous version
private static void DownloadSomeTextSync()
{
using (var client = new WebClient())
{
Console.WriteLine(
client.DownloadString(new Uri(string.Format(
"http://{0}",
(Dns.GetHostAddresses("www.basta.net"))[0]))));
}
}
// Asynchronous version
private static async void DownloadSomeTextUsingTaskAsync()
{
using (var client = new WebClient())
{
Console.WriteLine(
await client.DownloadStringTaskAsync(new Uri(string.Format(
"http://{0}",
(await Dns.GetHostAddressesAsync("www.basta.net"))[0]))));
}
}

Sync vs. Async
Notice how similar the sync and async
versions are!
private static async void DownloadSomeTextUsingTaskAsync2()
{
using (var client = new WebClient())
{
try
{
var ipAddress = await Dns.GetHostAddressesAsync("www.basta.net");
var content = await client.DownloadStringTaskAsync(
new Uri(string.Format("htt://{0}", ipAddress[0])));
Console.WriteLine(content);
}
catch (Exception)
{
Console.WriteLine("Exception!");
}
}
}

Generated Code
Guidelines for async/await
Task ended in Canceled
state, OperationCanceledException will be thrown

 If
private async static void CancelTask()
{
try
{
var cancelSource = new CancellationTokenSource();
var result = await DoSomethingCancelledAsync(cancelSource.Token);
Console.WriteLine(result);
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled!");
}
}
private static Task<int> DoSomethingCancelledAsync(CancellationToken token)
{
// For demo purposes we ignore token and always return a cancelled task
var result = new TaskCompletionSource<int>();
result.SetCanceled();
return result.Task;
}

TPL
TaskCompletionSource<T>
Note that async API of WebClient uses
existing cancellation logic instead of
CancellationTokenSource
Workshop: Async and Parallel in C#
Guidelines for async/await
 Caller
 Async

runs in parallel to awaited methods

methods sometimes do not run async (e.g. if task
is already completed when async is reached)
Guidelines for async/await (UI Layer)
 async/await

use SynchronizationContext to
execute the awaiting method  UI thread in case of UI
layer

 Use

Task.ConfigureAwait to disable this behavior

E.g. inside library to enhance performance
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = this;
this.ListBoxContent = new ObservableCollection<string>();
this.InitializeComponent();
this.ListBoxContent.Add("Started");
this.Loaded += async (s, e) =>
{
for (int i = 0; i < 10; i++)
{
ListBoxContent.Add(await Task.Run(() =>
{
Thread.Sleep(1000);
return "Hello World!";
}));
}
this.ListBoxContent.Add("Finished");
};
}
public ObservableCollection<string> ListBoxContent { get; private set; }

Async/await im UI
Workshop: Async and Parallel in C#
Guidelines For Implementing Methods Ready For async/await


Return Task/Task<T>



Use postfix Async



If method support cancelling, add parameter of type
System.Threading.CancellationToken



If method support progress reporting, add IProgress<T> parameter



Only perform very limited work before returning to the caller (e.g. check arguments)



Directly throw exception only in case of usage errors
public class Program : IProgress<int>
{
static void Main(string[] args)
{
var finished = new AutoResetEvent(false);
PerformCalculation(finished);
finished.WaitOne();
}
private static async void PerformCalculation(AutoResetEvent finished)
{
Console.WriteLine(await CalculateValueAsync(
42,
CancellationToken.None,
new Program()));
finished.Set();
}
public void Report(int value)
{
Console.WriteLine("Progress: {0}", value);
}

Progress Reporting
private static Task<int> CalculateValueAsync(
int startingValue,
CancellationToken cancellationToken,
IProgress<int> progress)
{
if (startingValue < 0)
{
// Usage error
throw new ArgumentOutOfRangeException("startingValue");
}
return Task.Run(() =>
{
int result = startingValue;
for (int outer = 0; outer < 10; outer++)
{
cancellationToken.ThrowIfCancellationRequested();
// Do some calculation
Thread.Sleep(500);
result += 42;
progress.Report(outer + 1);
}

return result;
});
}
}

Cancellation
private static async void PerformCalculation(AutoResetEvent
finished)
{
try
{
var cts = new CancellationTokenSource();
Task.Run(() =>
{
Thread.Sleep(3000);
cts.Cancel();
});
var result = await CalculateValueAsync(
42,
cts.Token,
new Program());
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancelled!");
}
finished.Set();
}

Cancellation
private static Task<int> CalculateValueAsync(
int startingValue,
CancellationToken cancellationToken,
IProgress<int> progress)
{
if (startingValue < 0)
{
// By definition the result has to be 0 if startingValue < 0
return Task.FromResult(0);
}
return Task.Run(() =>
{
[…]
});
}

Task.FromResult
Note how
Task.FromResult is used
to return a pseudo-task
Note that you could use
TaskCompletionSource
instead
namespace MvcApplication2.Controllers
{
public class BlogController : ApiController
{
// GET api/values/5
public async Task<BlogItem> Get(int id)
{
// Open context to underlying SQL database
using (var context = new BlogContext())
{
// Make sure that it contains database
await context.GenerateDemoDataAsync();
// Build the query
var blogs = context
.BlogItems
.Where(b => b.BlogId == id);
// Execute query
return await blogs.FirstOrDefaultAsync();
}
}
}
}

Async Web API
namespace MvcApplication2.Tests.Controllers
{
[TestClass]
public class BlogControllerTest
{
[TestMethod]
public async Task GetById()
{
BlogController controller = new BlogController();
var result = await controller.Get(1);
Assert.IsNotNull(result);
result = await controller.Get(99);
Assert.IsNull(result);
}
}
}

Async Unit Test
BASTA! Spring 2014

Rainer Stropek
software architects gmbh

Q&A

Mail rainer@timecockpit.com
Web http://www.timecockpit.com
Twitter @rstropek

Thank your for coming!
Saves the day.
is the leading time tracking solution for knowledge workers.
Graphical time tracking calendar, automatic tracking of your work using
signal trackers, high level of extensibility and customizability, full support to
work offline, and SaaS deployment model make it the optimal choice
especially in the IT consulting business.
Try
for free and without any risk. You can get your trial
account at http://www.timecockpit.com. After the trial period you can use
for only 0,20€ per user and day without a minimal subscription time and
without a minimal number of users.
ist die führende Projektzeiterfassung für Knowledge Worker.
Grafischer Zeitbuchungskalender, automatische Tätigkeitsaufzeichnung
über Signal Tracker, umfassende Erweiterbarkeit und Anpassbarkeit, volle
Offlinefähigkeit und einfachste Verwendung durch SaaS machen es zur
Optimalen Lösung auch speziell im IT-Umfeld.
Probieren Sie
kostenlos und ohne Risiko einfach aus. Einen
Testzugang erhalten Sie unter http://www.timecockpit.com. Danach nutzen
Sie
um nur 0,20€ pro Benutzer und Tag ohne Mindestdauer
und ohne Mindestbenutzeranzahl.

Weitere ähnliche Inhalte

Was ist angesagt?

Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSarah El-Atm
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEHitesh Mohapatra
 
Testing Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyTesting Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyMatthew Beale
 
Learn ASP.NET AJAX in 5 Minutes
Learn ASP.NET AJAX in 5 MinutesLearn ASP.NET AJAX in 5 Minutes
Learn ASP.NET AJAX in 5 Minutescode-kernel
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryKishor Kumar
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtupt k
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelinescpsitgmbh
 

Was ist angesagt? (20)

Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
Asp.net tips
Asp.net tipsAsp.net tips
Asp.net tips
 
Symfony2 Components - The Event Dispatcher
Symfony2 Components - The Event DispatcherSymfony2 Components - The Event Dispatcher
Symfony2 Components - The Event Dispatcher
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 
Testing Ember Apps: Managing Dependency
Testing Ember Apps: Managing DependencyTesting Ember Apps: Managing Dependency
Testing Ember Apps: Managing Dependency
 
Learn ASP.NET AJAX in 5 Minutes
Learn ASP.NET AJAX in 5 MinutesLearn ASP.NET AJAX in 5 Minutes
Learn ASP.NET AJAX in 5 Minutes
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with Celery
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 

Ähnlich wie Workshop: Async and Parallel in C#

Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4Wei Sun
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
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
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel ProcessingRTigger
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
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
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Paco de la Cruz
 
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
 
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
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKMifeng
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 

Ähnlich wie Workshop: Async and Parallel in C# (20)

Asynchronous in dot net4
Asynchronous in dot net4Asynchronous in dot net4
Asynchronous in dot net4
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
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#
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Parallel Processing
Parallel ProcessingParallel Processing
Parallel Processing
 
Async pattern
Async patternAsync pattern
Async pattern
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
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
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
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
 
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
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDK
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 

Kürzlich hochgeladen

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 

Kürzlich hochgeladen (20)

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 

Workshop: Async and Parallel in C#

  • 2. BASTA! Spring 2014 Rainer Stropek Async und Parallel software architects gmbh Web http://www.timecockpit.com Mail rainer@timecockpit.com Twitter @rstropek Workshop Saves the day.
  • 3. Async Programming In C# and .NET 4.5
  • 4. private static void DownloadSomeTextSync() { using (var client = new WebClient()) { Console.WriteLine( client.DownloadString(new Uri(string.Format( "http://{0}", (Dns.GetHostAddresses("www.basta.net"))[0])))); } } Synchronous
  • 5. private static void DownloadSomeText() { var finishedEvent = new AutoResetEvent(false); // Notice the IAsyncResult-pattern here Dns.BeginGetHostAddresses("www.basta.net", GetHostEntryFinished, finishedEvent); finishedEvent.WaitOne(); } private static void GetHostEntryFinished(IAsyncResult result) { var hostEntry = Dns.EndGetHostAddresses(result); using (var client = new WebClient()) { // Notice the Event-based asynchronous pattern here client.DownloadStringCompleted += (s, e) => { Console.WriteLine(e.Result); ((AutoResetEvent)result.AsyncState).Set(); }; client.DownloadStringAsync(new Uri(string.Format( "http://{0}", hostEntry[0].ToString()))); } } IAsyncResult Pattern
  • 6. private static void DownloadSomeText() { var finishedEvent = new AutoResetEvent(false); // Notice the IAsyncResult-pattern here Dns.BeginGetHostAddresses( "www.basta.net", (result) => { var hostEntry = Dns.EndGetHostAddresses(result); using (var client = new WebClient()) { // Notice the Event-based asynchronous pattern here client.DownloadStringCompleted += (s, e) => { Console.WriteLine(e.Result); ((AutoResetEvent)result.AsyncState).Set(); }; client.DownloadStringAsync(new Uri(string.Format( "http://{0}", hostEntry[0].ToString()))); } }, finishedEvent); finishedEvent.WaitOne(); } IAsyncResult Pattern With Lambdas
  • 7. private static void DownloadSomeTextUsingTask() { Dns.GetHostAddressesAsync("www.basta.net") .ContinueWith(t => { using (var client = new WebClient()) { return client.DownloadStringTaskAsync( new Uri(string.Format( "http://{0}", t.Result[0].ToString()))); } }) .ContinueWith(t2 => Console.WriteLine(t2.Unwrap().Result)) .Wait(); } TPL Notice the use of the new Task Async Pattern APIs in .NET 4.5 here
  • 8. Rules For Async Method Signatures  Method  Return name ends with Async value Task if sync version has return type void Task<T> if sync version has return type T  Avoid out and ref parameters Use e.g. Task<Tuple<T1, T2, …>> instead
  • 9. // Synchronous version private static void DownloadSomeTextSync() { using (var client = new WebClient()) { Console.WriteLine( client.DownloadString(new Uri(string.Format( "http://{0}", (Dns.GetHostAddresses("www.basta.net"))[0])))); } } // Asynchronous version private static async void DownloadSomeTextUsingTaskAsync() { using (var client = new WebClient()) { Console.WriteLine( await client.DownloadStringTaskAsync(new Uri(string.Format( "http://{0}", (await Dns.GetHostAddressesAsync("www.basta.net"))[0])))); } } Sync vs. Async Notice how similar the sync and async versions are!
  • 10. private static async void DownloadSomeTextUsingTaskAsync2() { using (var client = new WebClient()) { try { var ipAddress = await Dns.GetHostAddressesAsync("www.basta.net"); var content = await client.DownloadStringTaskAsync( new Uri(string.Format("htt://{0}", ipAddress[0]))); Console.WriteLine(content); } catch (Exception) { Console.WriteLine("Exception!"); } } } Generated Code
  • 11. Guidelines for async/await Task ended in Canceled state, OperationCanceledException will be thrown  If
  • 12. private async static void CancelTask() { try { var cancelSource = new CancellationTokenSource(); var result = await DoSomethingCancelledAsync(cancelSource.Token); Console.WriteLine(result); } catch (OperationCanceledException) { Console.WriteLine("Cancelled!"); } } private static Task<int> DoSomethingCancelledAsync(CancellationToken token) { // For demo purposes we ignore token and always return a cancelled task var result = new TaskCompletionSource<int>(); result.SetCanceled(); return result.Task; } TPL TaskCompletionSource<T>
  • 13. Note that async API of WebClient uses existing cancellation logic instead of CancellationTokenSource
  • 15. Guidelines for async/await  Caller  Async runs in parallel to awaited methods methods sometimes do not run async (e.g. if task is already completed when async is reached)
  • 16. Guidelines for async/await (UI Layer)  async/await use SynchronizationContext to execute the awaiting method  UI thread in case of UI layer  Use Task.ConfigureAwait to disable this behavior E.g. inside library to enhance performance
  • 17. public partial class MainWindow : Window { public MainWindow() { this.DataContext = this; this.ListBoxContent = new ObservableCollection<string>(); this.InitializeComponent(); this.ListBoxContent.Add("Started"); this.Loaded += async (s, e) => { for (int i = 0; i < 10; i++) { ListBoxContent.Add(await Task.Run(() => { Thread.Sleep(1000); return "Hello World!"; })); } this.ListBoxContent.Add("Finished"); }; } public ObservableCollection<string> ListBoxContent { get; private set; } Async/await im UI
  • 19. Guidelines For Implementing Methods Ready For async/await  Return Task/Task<T>  Use postfix Async  If method support cancelling, add parameter of type System.Threading.CancellationToken  If method support progress reporting, add IProgress<T> parameter  Only perform very limited work before returning to the caller (e.g. check arguments)  Directly throw exception only in case of usage errors
  • 20. public class Program : IProgress<int> { static void Main(string[] args) { var finished = new AutoResetEvent(false); PerformCalculation(finished); finished.WaitOne(); } private static async void PerformCalculation(AutoResetEvent finished) { Console.WriteLine(await CalculateValueAsync( 42, CancellationToken.None, new Program())); finished.Set(); } public void Report(int value) { Console.WriteLine("Progress: {0}", value); } Progress Reporting
  • 21. private static Task<int> CalculateValueAsync( int startingValue, CancellationToken cancellationToken, IProgress<int> progress) { if (startingValue < 0) { // Usage error throw new ArgumentOutOfRangeException("startingValue"); } return Task.Run(() => { int result = startingValue; for (int outer = 0; outer < 10; outer++) { cancellationToken.ThrowIfCancellationRequested(); // Do some calculation Thread.Sleep(500); result += 42; progress.Report(outer + 1); } return result; }); } } Cancellation
  • 22. private static async void PerformCalculation(AutoResetEvent finished) { try { var cts = new CancellationTokenSource(); Task.Run(() => { Thread.Sleep(3000); cts.Cancel(); }); var result = await CalculateValueAsync( 42, cts.Token, new Program()); } catch (OperationCanceledException) { Console.WriteLine("Cancelled!"); } finished.Set(); } Cancellation
  • 23. private static Task<int> CalculateValueAsync( int startingValue, CancellationToken cancellationToken, IProgress<int> progress) { if (startingValue < 0) { // By definition the result has to be 0 if startingValue < 0 return Task.FromResult(0); } return Task.Run(() => { […] }); } Task.FromResult Note how Task.FromResult is used to return a pseudo-task Note that you could use TaskCompletionSource instead
  • 24. namespace MvcApplication2.Controllers { public class BlogController : ApiController { // GET api/values/5 public async Task<BlogItem> Get(int id) { // Open context to underlying SQL database using (var context = new BlogContext()) { // Make sure that it contains database await context.GenerateDemoDataAsync(); // Build the query var blogs = context .BlogItems .Where(b => b.BlogId == id); // Execute query return await blogs.FirstOrDefaultAsync(); } } } } Async Web API
  • 25. namespace MvcApplication2.Tests.Controllers { [TestClass] public class BlogControllerTest { [TestMethod] public async Task GetById() { BlogController controller = new BlogController(); var result = await controller.Get(1); Assert.IsNotNull(result); result = await controller.Get(99); Assert.IsNull(result); } } } Async Unit Test
  • 26. BASTA! Spring 2014 Rainer Stropek software architects gmbh Q&A Mail rainer@timecockpit.com Web http://www.timecockpit.com Twitter @rstropek Thank your for coming! Saves the day.
  • 27. is the leading time tracking solution for knowledge workers. Graphical time tracking calendar, automatic tracking of your work using signal trackers, high level of extensibility and customizability, full support to work offline, and SaaS deployment model make it the optimal choice especially in the IT consulting business. Try for free and without any risk. You can get your trial account at http://www.timecockpit.com. After the trial period you can use for only 0,20€ per user and day without a minimal subscription time and without a minimal number of users.
  • 28. ist die führende Projektzeiterfassung für Knowledge Worker. Grafischer Zeitbuchungskalender, automatische Tätigkeitsaufzeichnung über Signal Tracker, umfassende Erweiterbarkeit und Anpassbarkeit, volle Offlinefähigkeit und einfachste Verwendung durch SaaS machen es zur Optimalen Lösung auch speziell im IT-Umfeld. Probieren Sie kostenlos und ohne Risiko einfach aus. Einen Testzugang erhalten Sie unter http://www.timecockpit.com. Danach nutzen Sie um nur 0,20€ pro Benutzer und Tag ohne Mindestdauer und ohne Mindestbenutzeranzahl.