Programação assíncrona com c sharp

Download Programação assíncrona com c sharp

Post on 10-May-2015

279 views

Category:

Technology

1 download

Embed Size (px)

DESCRIPTION

Programao assncrona com C#

TRANSCRIPT

<ul><li>1.Programao assncrona com C# 5 Andr Bires @ Take.net Janeiro de 2014</li></ul> <p>2. Il Pizzeria Ritardato 3. Pizzeria Ritardato 5 garons 10 mesas 4. Pizzeria Ritardato Garom espera na cozinha o pedido 5. Pizzeria Ritardato + de 5 pedidos = Clientes esperando 6. Pizzeria Ritardato Contratao de + 5 garons Total = 10 7. Pizzeria Ritardato Custo &gt; Receita = Prejuzos 8. Il Pizzeria Veloce 9. Pizzeria Veloce 3 garons 10 mesas 10. Pizzeria Veloce Garom leva pedido na cozinha e volta para o balco 11. Pizzeria Veloce Campainha Garom pedido != garom entrega 12. Pizzeria Veloce Aumento da freguesia 3 garons + que suficientes Ampliao para 15 mesas 13. Pizzeria Veloce Mesmo custo com Maior receita = Maior eficincia 14. ? 15. ! 16. Programao assncrona Uso eficiente dos recursos computacionais 17. NUNCA bloquear uma thread 18. Thread bloqueada = Dinheiro jogado fora 19. Thread bloqueada = Destruio da natureza 20. Programao assncrona Retorno ao threadpool Notificao de concluso 21. No o mesmo que programao paralela! 22. Programao assncrona Pizzaria: Servidor Mesa/cliente: Aplicao Garom: Thread Salrio do garom: Memria da thread Balco: Thread pool 23. Programao assncrona Pedido: Requisio externa Pizzaiolo: Servio externo Pizza: Resultado da requisio Campainha: Notificao 24. Programao assncrona com C# 5 25. Programao assncrona com C# Asynchronous Programming Model (APM) 26. Programao assncrona com C# Asynchronous Programming Model (APM) Event-based Asynchronous Pattern (EAP) 27. Programao assncrona com C# Asynchronous Programming Model (APM) Event-based Asynchronous Pattern (EAP) Task-based Asynchronous Pattern (TAP) 28. Programao assncrona com C# Asynchronous Programming Model (APM) Event-based Asynchronous Pattern (EAP) Task-based Asynchronous Pattern (TAP) 29. Task-based Asynchronous Pattern Task ou Task C# 4 Task = Promisse ou Future 30. Task-based Asynchronous Pattern () =&gt; { } Threadpool 31. Task-based Asynchronous Pattern privatevoidExample1Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Tasktask=Task.Run(()=&gt;GetName(1)); nameTextBox.Text=task.Result; toolStripStatusLabel.Text="Done"; } 32. Task-based Asynchronous Pattern privatevoidExample1Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Tasktask=Task.Run(()=&gt;GetName(1)); nameTextBox.Text=task.Result; toolStripStatusLabel.Text="Done"; } 33. Task-based Asynchronous Pattern ContinueWith 34. Task-based Asynchronous Pattern privatevoidExample2Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Task.Run(()=&gt;GetName(1)) .ContinueWith(t=&gt; this.Invoke(newAction(()=&gt; { nameTextBox.Text=t.Result; toolStripStatusLabel.Text="Done"; })) ); } 35. Task-based Asynchronous Pattern privatevoidExample2Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Task.Run(()=&gt;GetName(1)) .ContinueWith(t=&gt; this.Invoke(newAction(()=&gt; { nameTextBox.Text=t.Result; toolStripStatusLabel.Text="Done"; })) ); } 36. Task-based Asynchronous Pattern privatevoidExample2Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Task.Run(()=&gt;GetName(1)) .ContinueWith(t=&gt; this.Invoke(newAction(()=&gt; { nameTextBox.Text=t.Result; toolStripStatusLabel.Text="Done"; })) ); } 37. Task-based Asynchronous Pattern privatevoidExample2Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; Task.Run(()=&gt;GetName(1)) .ContinueWith(t=&gt; this.Invoke(newAction(()=&gt; { nameTextBox.Text=t.Result; toolStripStatusLabel.Text="Done"; })) ); } 38. Task-based Asynchronous Pattern privatevoidExample1Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; for(inti=0;iGetName(1)); nameTextBox.AppendText(task.Result); nameTextBox.AppendText(Environment.NewLine); } toolStripStatusLabel.Text="Done"; } 39. privatevoidExample2Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; GetNames(Convert.ToInt32(repeatNumericUpDown.Value)); } privatevoidGetNames(intremaining) { Task.Run(()=&gt;GetName(1)) .ContinueWith(t=&gt; this.Invoke(newAction(()=&gt; { nameTextBox.AppendText(t.Result); nameTextBox.AppendText(Environment.NewLine); remaining--; if(remaining&gt;0) { GetNames(remaining); } else { toolStripStatusLabel.Text="Done"; } }) ) ); } 40. Task-based Asynchronous Pattern C# 5.0 (.NET 4.5) 41. async 42. await 43. Task-based Asynchronous Pattern Mtodo I/O que retorne uma Task Event handler assncrono 44. Task-based Asynchronous Pattern privateasyncvoidExample3Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; nameTextBox.Text=awaitGetNameAsync(1); toolStripStatusLabel.Text="Done"; } 45. Task-based Asynchronous Pattern privateasyncvoidExample3Button_Click(objectsender,EventArgse) { toolStripStatusLabel.Text="CallingtheAPI..."; for(inti=0;i { returnGetName(id); }); } privatestringGetName(intid) { //Synchronousimplemementation } 55. Task-based Asynchronous Pattern privateTaskGetNameAsyncWrapper(intid) { returnTask.Run(()=&gt; { returnGetName(id); }); } privatestringGetName(intid) { //Synchronousimplemementation } 56. Task-based Asynchronous Pattern privateasyncTaskGetNameAsync(intid) { stringurl=string.Format("http://localhost:3803/names/{0}",id); using(varclient=newHttpClient()) { varhttpResponseMessage=awaitclient.GetAsync(url); if(httpResponseMessage.IsSuccessStatusCode) { returnawaithttpResponseMessage.Content .ReadAsStringAsync(); } else { returnhttpResponseMessage.ReasonPhrase; } } } 57. Task-based Asynchronous Pattern Cdigo legado requer muitas alteraes 58. async = infec o 59. Task-based Asynchronous Pattern publicstringGet(intid,booldelay=false) { if(delay) { //Simulaumachamadaexterna,comobancodedados Thread.Sleep(3000); } returnstring.Format( "{0}{1}", _firstNames[_random.Next(_firstNames.Length-1)], _lastNames[_random.Next(_lastNames.Length-1)]); } 60. Task-based Asynchronous Pattern publicasyncTaskGetAsync(intid,booldelay=false) { if(delay) { //Simulaumachamadaexterna,comobancodedados awaitTask.Delay(3000); } returnstring.Format( "{0}{1}", _firstNames[_random.Next(_firstNames.Length-1)], _lastNames[_random.Next(_lastNames.Length-1)]); } 61. Task-based Asynchronous Pattern Boas prticas: async void apenas em event handlers ConfigureAwait(false) em bibliotecas 62. Task-based Asynchronous Pattern Callstack diferente do cdigo sncrono 63. ? </p>