Best Practices for Using async and await

25

Transcript of Best Practices for Using async and await

Page 1: Best Practices for Using async and await
Page 2: Best Practices for Using async and await

Dobre prakse pri uporabi async in awaitDamir Arh, Razum d.o.o.Microsoft MVP@DamirArhhttp://www.damirscorner.com

Page 3: Best Practices for Using async and await

AgendaOsnoveasync void je nevarenLažne asinhrone in sinhrone metodeConfigureAwait(false)?

Page 4: Best Practices for Using async and await

Sinhrono : asinhrono

O odzivnem uporabniškem vmesniku

Page 5: Best Practices for Using async and await

private void OnSync(object sender, RoutedEventArgs e){ StatusText.Text = "Processing..."; Thread.Sleep(_sleepPeriod); StatusText.Text = String.Empty;}

Sinhrono izvajanje

Glavna nit

Page 6: Best Practices for Using async and await

private async void OnAsync(object sender, RoutedEventArgs e){ StatusText.Text = "Processing..."; await Task.Delay(_sleepPeriod); StatusText.Text = String.Empty;}

Asinhrono izvajanje

Glavna nit

Page 7: Best Practices for Using async and await

async void?

Ne, hvala!

Page 8: Best Practices for Using async and await

async voidprivate async void OnGetData(object sender, RoutedEventArgs e){ try { DownloadMessages(); await Task.Delay(75); StatusText.Text = $"Messages received: {_messages.Count}"; } catch (Exception exception) { StatusText.Text = exception.Message; }}

Glavna nit

private async void DownloadMessages(){ _messages = await _repository.GetMessagesAsync();}

Page 9: Best Practices for Using async and await

Lovljenje izjemprivate async void OnGetData(object sender, RoutedEventArgs e){ try { DownloadMessages(); await Task.Delay(75); StatusText.Text = $"Messages received: {_messages.Count}"; } catch (Exception exception) { StatusText.Text = exception.Message; }}

Glavna nit

private async void DownloadMessages(){ _messages = await _repository.GetMessagesAsync();}

Page 10: Best Practices for Using async and await

Popravljena kodaprivate async void OnGetData(object sender, RoutedEventArgs e){ try { await DownloadMessagesAsync(); await Task.Delay(75); StatusText.Text = $"Messages received: {_messages.Count}"; } catch (Exception exception) { StatusText.Text = exception.Message; }}

Glavna nit

private async Task DownloadMessagesAsync(){ _messages = await _repository.GetMessagesAsync();}

Page 11: Best Practices for Using async and await

Lažno predstavljanje

Ni vse asinhrono, kar je async

Page 12: Best Practices for Using async and await

Testna kodavar tasks = new Task[_iterations];var stopwatch = new Stopwatch();

stopwatch.Start();for (int i = 0; i < _iterations; i++){ tasks[i] = AsyncService.CallAsync(i);}Task.WaitAll(tasks);stopwatch.Stop();

var duration = stopwatch.ElapsedMilliseconds;

Page 13: Best Practices for Using async and await

Prava in lažna implementacijapublic async Task TrueAsync(int index){ Console.WriteLine($"Start {index}"); await Task.Delay(millis); Console.WriteLine($"End {index}");}

public async Task FakeAsync(int index){ return await Task.Run(() => { Console.WriteLine($"Start {index}"); Thread.Sleep(Millis); Console.WriteLine($"End {index}"); });}

Page 14: Best Practices for Using async and await

Pravo asinhrono izvajanjezačetek 1

konec 4

začetek 2začetek 3začetek 4

konec 2konec 3konec 1

Page 15: Best Practices for Using async and await

konec 1 konec 2 konec 3 konec 4

Vrsta

Lažno asinhrono izvajanje

začetek 1začetek 2

začetek n

začetek 5

začetek 3začetek 4

začetek 6

Zaloga niti

konec 5

Page 16: Best Practices for Using async and await

V smrtnem objemu

Glavna nit je le ena

Page 17: Best Practices for Using async and await

Smrtni objemprivate void OnDeadlock(object sender, RoutedEventArgs e){ var result = GetAsync().Result;}

Glavna nit

private async Task<string> GetAsync(){ await Task.Delay(500); return String.Empty;}

Page 18: Best Practices for Using async and await

Popravljena kodaprivate async void OnDeadlock(object sender, RoutedEventArgs e){ var result = await GetAsync().Result;}

private async Task<string> GetAsync(){ await Task.Delay(500); return String.Empty;}

Glavna nit

Page 19: Best Practices for Using async and await

ConfigureAwait pomagaNe naredite si medvedje usluge

Page 20: Best Practices for Using async and await

SynchronizationContextAbstrakcija privzetega izvajalnega kontekstaOdvisen od tipa aplikacijeWindows FormsWPFASP.NET

ConfigureAwait odloča o vračanju na privzeti kontekstV aplikaciji običajno zaželenoV knjižnicah tipično nepotrebno

Page 21: Best Practices for Using async and await

Ključni poudarkiUporabljajte async void le pri odzivih na dogodkeZaloga niti je omejen vir v aplikacijiUporabljajte za procesorsko zahtevne operacijeNe uporabljajte za vhodno-izhodne operacije

Uporabljajte asinhrone in sinhrone operacije kot takšne

Page 23: Best Practices for Using async and await
Page 24: Best Practices for Using async and await

Izpolnite anketo! Vam je bilo predavanje všeč? Ste se naučili kaj novega?

Vaše mnenje nam veliko pomeni!

Da bo NT konferenca prihodnje leto še boljša, vas prosimo, da izpolnite anketo o zadovoljstvu, ki jo najdete v svojem NTK spletnem profilu.

Page 25: Best Practices for Using async and await

© 2015 Microsoft Corporation. All rights reserved.