Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();

Slides:



Advertisements
Similar presentations
Chapter 6 - VB 2005 by Schneider1 Do Loop Syntax Do While condition statement(s) Loop Condition is tested, If it is True, the loop is run. If it is False,
Advertisements

TechReady 16 4/1/2017 Async Clinic
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
Practical Programming COMP153-08S Lecture: Repetition Continued.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
var data = DownloadData(...); ProcessData(data); var future = DownloadDataAsync(...); future.ContinueWith(data => ProcessData(data));
Cole Durdan.  What is asynchronous programming?  Previous patterns  Task Based Async Programming .NET 4.5 Keywords  What happens in an async. method?
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Adjunct Professor: U. of Illinois, Chicago and Loyola University Chicago
Asynchronous programming Deadlock All The Things!.
please wait for the next slide clicking won’t make it come any faster.
Principles Async void is a “fire-and-forget” mechanism… The caller is unable to know when an async void has finished The caller is unable.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Enforcing Mutual Exclusion Message Passing. Peterson’s Algorithm for Processes P0 and P1 void P0() { while( true ) { flag[ 0 ] = false; /* remainder */
1 Thread Pools Representation and Management of Data on the Internet.
Async void is only for top-level event handlers. Use TaskCompletionSource to wrap Tasks around events. Use the threadpool for CPU-bound code, but not.
Async void is only for top-level event handlers. Use the threadpool for CPU-bound code, but not IO-bound. Use TaskCompletionSource to wrap Tasks around.
Managed Code Generics Language Integrated Query Dynamic + Language Parity C# VB 11.0 Windows Runtime + Asynchrony C# VB 7.0 C# VB.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Joe Hummel, PhD Technical Staff: Pluralsight Adjunct Professor: UIC, LUC
DEV301. // Synchronous TResult Foo(...); // Asynchronous Programming Model (APM) IAsyncResult BeginFoo(..., AsyncCallback callback, object state);
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
please wait for the next slide clicking won’t make it come any faster.
Exceptions Handling Exceptionally Sticky Problems.
private void Goto2(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var app = App.Current as Common.BootStrapper; var nav = app.NavigationService;
Parallel Programming: Responsiveness vs. Performance Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois,
public static void PausePrintAsync() { ThreadPool.QueueUserWorkItem(_ => PausePrint()); } public static Task PausePrintAsync() { return Task.Run(()
Joe Hummel, PhD Microsoft MVP Visual C++ Technical Staff: Pluralsight, LLC Professor: U. of Illinois, Chicago stuff:
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Future of VB and C# Lucian Wischik VB Language PM Microsoft.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView();
Module 3: Using Microsoft.NET- Based Languages. Overview Overview of the.NET-Based Languages Comparison of the.NET-Based Languages.
ICS 313: Programming Language Theory Chapter 13: Concurrency.

PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
IAsyncResult ar = BeginSomething(…); // Do other work, checking ar.IsCompleted int result = EndSomething(ar);
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
TAP into async programming
Образец заголовка Образец текста –Второй уровень Третий уровень –Четвертый уровень »Пятый уровень Тема: Task Parallel Library Крыжановский Анатолий.
please wait for the next slide clicking won’t make it come any faster.
Chapter 8-Exception Handling/ Robust Programming.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET library developers : with knowledge of async/await in C# / VB interested in low-level.
Integral Users will interact with your app on a big screen with keyboard and mouse.
Visual Basic. The Close Method The Close method is used to close a form. To close a form use the keyword Me to refer to the form. Me.Close()
33) static void Main() { Action operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0);
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
MIC305 Week 6 Beyond controls Review of properties Differences with VB6: using classes and instances Programming constructs.
TOPICS WHAT YOU’LL LEAVE WITH WHO WILL BENEFIT FROM THIS TALK.NET developers: familiar with parallel programming support in Visual Studio 2010 and.NET.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
Computer Science Up Down Controls, Decisions and Random Numbers.
Modern Programming Tools And Techniques-I
Thread Pools (Worker Queues) cs
5/16/2018 © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks.
Thread Pools (Worker Queues) cs
Handling Exceptionally Sticky Problems
3rd prep. – 2nd Term MOE Book Questions.
Cert Exam Prep: Exam : Programming with C#
12 Asynchronous Programming
البرمجة بلغة الفيجول بيسك ستوديو
Multithreaded Programming
Build /2/2019 © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks.
Using threads for long running tasks.
Eighth step for Learning C++ Programming
Handling Exceptionally Sticky Problems
Testing servers.
03 | Async Programming & Networking Intro
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Click async Task LoadSettingsAsync() { await IO.Network.DownloadAsync(path); } async void Button1_Click(){ await LoadSettingsAsync(); UpdateView(); } Click Message pump Task... DownloadAsync Task... LoadSettingsAsync Download LoadSettings

TaskAsync await

// Q. User mistakenly clicks twice, resulting in multiple purchases? private async void btnPurchase_Click(object sender, RoutedEventArgs e) { label1.Text = "Purchasing..."; await DoPurchaseAsync(product.code); label1.Text += "Completed!"; } // A. Guard against re-entrancy at the await points private async void btnPurchase_Click(object sender, RoutedEventArgs e) { btnPurchase.IsEnabled = false; btnPurchase.Content = "Purchasing..."; await DoPurchaseAsync(product.code); btnPurchase.Content = "Purchase!"; btnPurchase.IsEnabled = true; // TODO: do this re-enabling within a "finally" block }

' In VB, the expression itself determines void- or Task-returning (not the context). Dim void_returning = Async Sub() Await LoadAsync() : m_Result = "done" End Sub Dim task_returning = Async Function() Await LoadAsync() : m_Result = "done" End Function ' If both overloads are offered, you must give it Task-returning. Await Task.Run(Async Function()... End Function) // In C#, the context determines whether async lambda is void- or Task-returning. Action a1 = async () => { await LoadAsync(); m_Result="done"; }; Func a2 = async () => { await LoadAsync(); m_Result="done"; }; // Q. Which one will it pick? await Task.Run( async () => { await LoadAsync(); m_Result="done"; }); // A. If both overloads are offered, it will pick Task-returning. Good! class Task { static public Task Run(Action a) {...} static public Task Run(Func a) {...}... }

// Usage: await storyboard1.PlayAsync(); public static async Task PlayAsync(this Storyboard storyboard) { var tcs = new TaskCompletionSource (); EventHandler lambda = (s,e) => tcs.TrySetResult(null); try { storyboard.Completed += lambda; storyboard.Begin(); await tcs.Task; } finally { storyboard.Completed -= lambda; } ' Usage: Await storyboard1.PlayAsync() Async Function PlayAsync(sb As Animation.Storyboard) As Task Dim tcs As New TaskCompletionSource(Of Object) Dim lambda As EventHandler(Of Object) = Sub() tcs.TrySetResult(Nothing) Try AddHandler sb.Completed, lambda sb.Begin() Await tcs.Task Finally RemoveHandler sb.Completed, lambda End Try End Function

// Usage: await button1.WhenClicked(); public static async Task WhenClicked(this Button button) { var tcs = new TaskCompletionSource (); RoutedEventHandler lambda = (s,e) => tcs.TrySetResult(null); try { button.Click += lambda; await tcs.Task; } finally { button.Click -= lambda; }

Async Function DragAsync(shape As UIElement, start As PointerRoutedEventArgs) As Task(Of Point) Dim tcs As New TaskCompletionSource(Of Point) Dim parent = CType(VisualTreeHelper.GetParent(shape), Windows.UI.Xaml.UIElement) Dim origPos = New Point(Canvas.GetLeft(shape), Canvas.GetTop(shape)) Dim origPt = start.GetCurrentPoint(parent).Position Dim lambdaReleased, lambdaMoved As PointerEventHandler lambdaReleased = Sub(s, e) tcs.TrySetResult(e.GetCurrentPoint(parent).Position) End Sub lambdaMoved = Sub(s, e) Dim pt = e.GetCurrentPoint(parent).Position Canvas.SetLeft(shape, origPos.X + pt.X - origPt.X) Canvas.SetTop(shape, origPos.Y + pt.Y - origPt.Y) End Sub shape.CapturePointer(start.Pointer) AddHandler shape.PointerMoved, lambdaMoved AddHandler shape.PointerReleased, lambdaReleased AddHandler shape.PointerCanceled, lambdaReleased AddHandler shape.PointerCaptureLost, lambdaReleased Try Return Await tcs.Task Finally shape.ReleasePointerCapture(start.Pointer) RemoveHandler shape.PointerMoved, lambdaMoved RemoveHandler shape.PointerReleased, lambdaReleased RemoveHandler shape.PointerCanceled, lambdaReleased RemoveHandler shape.PointerReleased, lambdaReleased End Try End Function ' Usage: ' ' Protected Overrides Async Sub OnPointerPressed(e As PointerRoutedEventArgs) ' Dim endpt = Await DragAsync(e.OriginalSource, e) ' End Sub ' Usage: ' ' Protected Overrides Async Sub OnPointerPressed(e As PointerRoutedEventArgs) ' Dim endpt = Await DragAsync(e.OriginalSource, e) ' End Sub

' Usage: Await Dispatcher.Run(Async Function()... End Function) Public Async Function Run(dispatcher As CoreDispatcher, asyncFunc As Func(Of Task)) As Task Dim task As Task = Nothing Await dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() task = asyncFunc()) Await task ' We're using "task" rather than TaskCompletionSource. ' That's because we need to rethrow any exceptions that might have come from asyncFunc. ' This way is easiest. End Function

Protected Async Sub OnResume(e As Navigation.NavigationEventArgs) ' While sound is playing... Dim rustleSoundTask = RustleSound.PlayAsync() Using wobbleCancel As New CancellationTokenSource '... wobble all the apples For Each apple In FreeApples AnimateAppleWobbleAsync(apple, wobbleCancel.Token).FireAndForget() Next ' Then stop wobbling once sound has finished Await rustleSoundTask wobbleCancel.Cancel() End Using End Sub

// table1.DataSource = LoadHousesSequentially(1,5); // table1.DataBind(); public List LoadHousesSequentially(int first, int last) { var loadedHouses = new List (); for (int i = first; i <= last; i++) { House house = House.Deserialize(i); loadedHouses.Add(house); } return loadedHouses; } work1 request in response out 500ms work2 work3 work4 work5

response out 300ms work1 work2 work3 work4 work5 Parallel.For request in

end1 start1 end2 start2 end3 start3 end4 start4 end5 start5 response out 500ms request in

1 end1 start1 2 end2 start2 3 end3 start3 5 end5 start5 end1 start1 end2 start2 end5 start5 response out ~200ms Parallel.For request in end3 start3 end4 start4

end2 start1 request in start2 start3 start4 start5 response out ~100ms end5 end1 end3 end4

public async Task > LoadHousesAsync(int first, int last) { var loadedHouses = new List (); var queue = new Queue (Enumerable.Range(first, last – first + 1)); // Throttle the rate of issuing requests... var worker1 = WorkerAsync(queue, loadedHouses); var worker2 = WorkerAsync(queue, loadedHouses); var worker3 = WorkerAsync(queue, loadedHouses); await Task.WhenAll(worker1, worker2, worker3); return loadedHouses; } private async Task WorkerAsync(Queue queue, List results) { while (queue.Count > 0) { int i = queue.Dequeue(); var house = await House.LoadFromDatabaseAsync(i); results.Add(house); } private async Task WorkerAsync(Queue queue, List results) { while (queue.Count > 0) { int i = queue.Dequeue(); var house = await House.LoadFromDatabaseAsync(i); results.Add(house); }

async void button1_Click(…) { Action work = CPUWork; await ScheduleAsync(work); … } async Task ScheduleAsync(Action work) { work(); } async void button1_Click(…) { Action work = CPUWork; await Task.Run(() => work()); … }

…; Task.Delay(1000); …; …; await Task.Delay(1000); …; Parallel.For(0, 10, async i => { await Task.Delay(1000); }); await Task.Factory.StartNew( async () => { await Task.Delay(1000); }); await Task.Run( async () => { await Task.Delay(1000); });

var tcs = new TaskCompletionSource (); Task.Run(delegate { T result = Foo(); tcs.SetResult(result); }); return tcs.Task; var tcs = new TaskCompletionSource (); Task.Run(delegate { try { T result = Foo(); tcs.SetResult(result); } catch(Exception e) { tcs.SetException(e); } }); return tcs.Task; void button1_Click(…) { FooAsync().Wait(); } async Task FooAsync() { await Task.Delay(1000); } async void button1_Click(…) { await FooAsync(); } async Task FooAsync() { await Task.Delay(1000); } async void button1_Click(…) { await FooAsync(); } async Task FooAsync() { await Task.Delay(1000).ConfigureAwait(false); }