SlideShare ist ein Scribd-Unternehmen logo
1 von 47
Programação assíncrona
              com C# 5
                 Giovanni Bassi
         giovanni@lambda3.com.br
                    @giovannibassi
              blog.lambda3.com.br
Giovanni Bassi
• Trouxe a Scrum.org, PSM e PSD pro Brasil
• Palestrante nacional e internacional (gestão,
  agile, engenharia e arquitetura de software)
• Programador
• tecnoretorica.com.br, blog.lambda3.com.br,
  dotnetarchitects.net
• Escalador e ciclista
• Não gerente
http://bit.ly/lambda3democracia
Evolução do C# e VB


                  C# 4.0 + VB 10.0
                                          Dinamismo + paridade nas
                                          linguagens
           C# 3.0 + VB 9.0
                                     Language Integrated Query

     C# 2.0 + VB 8.0
                               Generics

C# 1.0 + VB 7.0
                         Código gerenciado
Tendências
Tendências
• Aplicações cada vez mais conectadas
  – Mais latência
  – Mais problemas de responsividade da interface gráfica
    (IG)
  – Mais problemas de escalabilidade
• Programação assíncrona
  – Está se tornando a norma em aplicações escaladas e
    responsivas
  – APIs que são somente assíncronas, como JavaScript,
    Silverlight, Windows 8, Windows Phone
Evolução do C# e VB
                       C# 5.0 + VB 11.0
                                               Programação assíncrona

                  C# 4.0 + VB 10.0
                                          Dinamismo + paridade nas
                                          linguagens
           C# 3.0 + VB 9.0
                                     Language Integrated Query

     C# 2.0 + VB 8.0
                               Generics

C# 1.0 + VB 7.0
                         Código gerenciado
O que há de novo?


• Programação assíncrona       • Programação assíncrona
• Atributos de informação de   • Atributos de informação de
  chamada                        chamada
                               • Iterators
Assincronia em poucas palavras
• Síncrono  Espero o resultado antes de retonar
   – string DownloadString(...);


• Assíncrono  Retorne agora, chame de volta com o
  resultado
   – void DownloadStringAsync(..., Action<string> callback);


• Benefícios da assincronia
   – Responsividade da interface gráfica: libera as threads de IG
     para interação com o usuário
   – Escalabilidade do servidor: A thread pode ser reutilizada para
     outras requisições
Síncrono versus Assíncrono
var data = DownloadData(...);
ProcessData(data);




DownloadDataAsync(... , data => {
    ProcessData(data);
});
Síncrono versus Assíncrono
var data = DownloadData(...);
ProcessData(data);




DownloadDataAsync(... , data => {
    ProcessData(data);
});
Interface gráfica
assíncrona e responsiva
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

          Mensagens




        Thread de IG
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2




               
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2




               
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2




                             
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2




                             
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
             



                             
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
             



                            
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
             



                                                
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
          



                                                
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
           



                                                
Fluxo de controle assíncrono
 async void DoWorkAsync() {
     var t1 = ProcessFeedAsync("www.acme.com/rss");
     var t2 = ProcessFeedAsync("www.xyznews.com/rss");
     await Task.WhenAll(t1, t2);
     DisplayMessage("Done");
 }                               async Task ProcessFeedAsync(string url) {
                                     var text = await DownloadFeedAsync(url);
                                     var doc = ParseFeedIntoDoc(text);
                                     await SaveDocAsync(doc);
                                     ProcessLog.WriteEntry(url);
                                 }

         t1 t2
           



                                                
Como funciona?

async Task<XElement> GetRssAsync(string url) {
    var client = new WebClient();
    var task = client.DownloadStringTaskAsync(url);
    var text = await task;
    var xml = XElement.Parse(text);
    return xml;
}
Como funciona?

async Task<XElement> GetRssAsync(string url) {
    var client = new WebClient();
    var task = client.DownloadStringTaskAsync(url);
    var text = await task;
    var xml = XElement.Parse(text);
    return xml;
}                    Task<XElement> GetRssAsync(string url) {
                         var client = new WebClient();
                         var task = client.DownloadStringTaskAsync(url);
                         return task.ContinueWith(delegate
                         {
                             var text = task.Result;
                             var xml = XElement.Parse(text);
                             return xml;
                         });
                     }
Como funciona?
              Task<XElement> GetRssAsync(string url) {
                  var $builder = AsyncTaskMethodBuilder<XElement>.Create();
async Task<XElement> $state = 0;
                  var
                  TaskAwaiter<string> $a1;
GetRssAsync(string url) {
                  Action $resume = delegate {
    var client = new try {
                      WebClient();
    var task =            if ($state == 1) goto L1;
client.DownloadStringTaskAsync(url);new WebClient();
                          var client =
    var text = await task; task = client.DownloadStringTaskAsync(url);
                          var
                          $a1 = task.GetAwaiter();
    var xml = XElement.Parse(text);
    return xml;           if ($a1.IsCompleted) goto L1;
}                         $state = 1;
                          $a1.OnCompleted($resume);
                          return;
                      L1: var text = $a1.GetResult();
                          var xml = XElement.Parse(text);
                          $builder.SetResult(xml);
                      }
                      catch (Exception $ex) { $builder.SetException($ex); }
                  };
                  $resume();
                  return $builder.Task;
              }
Como funciona?
              Task<XElement> GetRssAsync(string url) {
                  var $builder = AsyncTaskMethodBuilder<XElement>.Create();
async Task<XElement> $state = 0;
                  var
                  TaskAwaiter<string> $a1;
GetRssAsync(string url) {
                  Action $resume = delegate {
    var client = new try {
                      WebClient();
    var task =            if ($state == 1) goto L1;
client.DownloadStringTaskAsync(url);new WebClient();
                          var client =
    var text = await task; task = client.DownloadStringTaskAsync(url);
                          var
                          $a1 = task.GetAwaiter();
    var xml = XElement.Parse(text);
    return xml;           if ($a1.IsCompleted) goto L1;
}                         $state = 1;
                          $a1.OnCompleted($resume);
                          return;
                      L1: var text = $a1.GetResult();
                          var xml = XElement.Parse(text);
                          $builder.SetResult(xml);
                      }
                      catch (Exception $ex) { $builder.SetException($ex); }
                  };
                  $resume();
                  return $builder.Task;
              }
Como funciona?
              Task<XElement> GetRssAsync(string url) {
                  var $builder = AsyncTaskMethodBuilder<XElement>.Create();
async Task<XElement> $state = 0;
                  var
                  TaskAwaiter<string> $a1;
GetRssAsync(string url) {
                  Action $resume = delegate {
    var client = new try {
                      WebClient();
    var task =            if ($state == 1) goto L1;
client.DownloadStringTaskAsync(url);new WebClient();
                          var client =
    var text = await task; task = client.DownloadStringTaskAsync(url);
                          var
                          $a1 = task.GetAwaiter();
    var xml = XElement.Parse(text);
    return xml;           if ($a1.IsCompleted) goto L1;
}                         $state = 1;
                          $a1.OnCompleted($resume);
                          return;
                      L1: var text = $a1.GetResult();
                          var xml = XElement.Parse(text);
                          $builder.SetResult(xml);
                      }
                      catch (Exception $ex) { $builder.SetException($ex); }
                  };
                  $resume();
                  return $builder.Task;
              }
Como funciona?
              Task<XElement> GetRssAsync(string url) {
                  var $builder = AsyncTaskMethodBuilder<XElement>.Create();
async Task<XElement> $state = 0;
                  var
                  TaskAwaiter<string> $a1;
GetRssAsync(string url) {
                  Action $resume = delegate {
    var client = new try {
                      WebClient();
    var task =            if ($state == 1) goto L1;
client.DownloadStringTaskAsync(url);new WebClient();
                          var client =
    var text = await task; task = client.DownloadStringTaskAsync(url);
                          var
                          $a1 = task.GetAwaiter();
    var xml = XElement.Parse(text);
    return xml;           if ($a1.IsCompleted) goto L1;
}                         $state = 1;
                          $a1.OnCompleted($resume);
                          return;
                      L1: var text = $a1.GetResult();
                          var xml = XElement.Parse(text);
                          $builder.SetResult(xml);
                      }
                      catch (Exception $ex) { $builder.SetException($ex); }
                  };
                  $resume();
                  return $builder.Task;
              }
Métodos assíncronos...
• São marcados com o novo modificador “async”
• Devem retornar void, Task ou Task<T>
• Usam o operador “await” para devolver controle
  cooperativamente
• Voltam a ser executados quando uma operação que estava em
  espera (await) conclui
• Podem esperar (await) qualquer coisa que implemente o
  “padrão de espera”
• Executam no contexto de sincronização de quem os chamou
• Permitem composição com as construções normais de
  programação
• Parecem com código normal e síncrono!
Depurando métodos
assíncronos
Async com ASP.NET ontem
public void AcaoAsync()
{
  AsyncManager.OutstandingOperations.Increment(5);
  var svc = new AsyncPatternSvc.Service1Client();
  AsyncManager.Parameters["textoFinal"] = "";
  svc.GetDataCompleted += (sender, args) =>
  {
     AsyncManager.Parameters["textoFinal"] =
          ((string)AsyncManager.Parameters["textoFinal"]) + args.Result + ", ";
     AsyncManager.OutstandingOperations.Decrement();
  };
  for (int i = 0; i < 5; i++)
     svc.GetDataAsync(i);
}
public ActionResult AcaoCompleted(string textoFinal)
{
  return View("RetornoServico", new AsyncModel { Resultado = textoFinal });
}
Async com ASP.NET hoje
public async Task<ActionResult> Acao()
{
  var svc = new TaskSvc.Service1Client();
  var resultados = await Task.WhenAll(
    from i in Enumerable.Range(0, 5)
    select svc.GetDataAsync(i));
  var textoFinal = string.Join(", ", resultados);
  return View("RetornoServico", new AsyncModel{
Resultado = textoFinal });
}
Suporte no .NET Framework

                             Outras…




Windows
Presentation                 ASP.NET
Foundation
WCF – Cliente/Servidor
Escalabilidade: Evitando novas threads
• Blocos síncronos lógicos esperando por requisições de
   rede:
 var feeds = (from url in urls select client.DownloadFeed(url)).ToArray();




 var feeds = await Task.WhenAll(from url in urls select client.DownloadFeedAsync(url));



    Sem novas threads!
Unificando a assincronia



• Um cenário assíncrono
  – Busca alguns links de vídeo no YouTube
  – Baixa dois vídeos ao mesmo tempo
  – Cria um novo vídeo a partir dos vídeos baixados
  – Salva o vídeo resultante
Unificando a assincronia



try {
    string[] videoUrls = await ScrapeYoutubeAsync(url);    // Rede
    Task<Video> t1 = DownloadVideoAsync(videoUrls[0]);     // Baixe 2 videos
    Task<Video> t2 = DownloadVideoAsync(videoUrls[1]);
    Video[] vids = await Task.WhenAll(t1, t2);             // Espere os 2
    Video v = await MashupVideosAsync(vids[0], vids[1]);   // CPU
    await v.SaveAsync(textbox.Text);                       // Entrada/Saída
}
catch (WebException ex) {
    ReportError(ex);
}
Métodos assíncronos
• (Quase) tão simples quanto código síncrono
• Unifica assincronia computacional, de rede e de
  E/S
• Permite servidores mais escaláveis
• IG mais responsiva
Obrigado!
           Giovanni Bassi
   giovanni@lambda3.com.br
              @giovannibassi
        blog.lambda3.com.br

Weitere ähnliche Inhalte

Andere mochten auch

Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platform
Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV PlatformLook and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platform
Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platformmiguelvinagre
 
Looking At Christmas Back In Time
Looking At Christmas Back In TimeLooking At Christmas Back In Time
Looking At Christmas Back In TimeJeanette Murphy
 
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52Voorbeelden voor Zeeland: Mediaregeling Limburg & e52
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52Bart Brouwers
 
Skema Bm Kertas2 Set3
Skema Bm Kertas2 Set3Skema Bm Kertas2 Set3
Skema Bm Kertas2 Set3Kay Aniza
 
Hyperlocal Introduction
Hyperlocal IntroductionHyperlocal Introduction
Hyperlocal IntroductionBart Brouwers
 
Fazendo Injeção de dependência com Unity 1.2
Fazendo Injeção de dependência com Unity 1.2Fazendo Injeção de dependência com Unity 1.2
Fazendo Injeção de dependência com Unity 1.2Giovanni Bassi
 
Social Network
Social NetworkSocial Network
Social NetworkSaLaPaO
 
3 Secrets Of Productivity
3 Secrets Of Productivity3 Secrets Of Productivity
3 Secrets Of ProductivityRussMack
 
Most Contagious 2008
Most Contagious 2008Most Contagious 2008
Most Contagious 2008Daniel Simon
 
MàQuines I Mecanismes
MàQuines I MecanismesMàQuines I Mecanismes
MàQuines I Mecanismesdiegobm
 
Univ Aizu week10 about computer
Univ Aizu week10 about  computerUniv Aizu week10 about  computer
Univ Aizu week10 about computerI M
 
Fontys business model generation & dichtbij
Fontys business model generation & dichtbijFontys business model generation & dichtbij
Fontys business model generation & dichtbijBart Brouwers
 
Пожизненное обучение: критика больших данных в образовании
Пожизненное обучение: критика больших данных в образованииПожизненное обучение: критика больших данных в образовании
Пожизненное обучение: критика больших данных в образованииIvan Travkin
 
The Crossroads of dichtbij.nl
The Crossroads of dichtbij.nlThe Crossroads of dichtbij.nl
The Crossroads of dichtbij.nlBart Brouwers
 
Учение и обучение в век равногогики
Учение и обучение в век равногогикиУчение и обучение в век равногогики
Учение и обучение в век равногогикиIvan Travkin
 
MàQuines I Mecanismes
MàQuines I MecanismesMàQuines I Mecanismes
MàQuines I Mecanismesdiegobm
 

Andere mochten auch (20)

Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platform
Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV PlatformLook and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platform
Look and Feel Issues and Usability at Imagenio Telefonica´s IPTV Platform
 
Looking At Christmas Back In Time
Looking At Christmas Back In TimeLooking At Christmas Back In Time
Looking At Christmas Back In Time
 
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52Voorbeelden voor Zeeland: Mediaregeling Limburg & e52
Voorbeelden voor Zeeland: Mediaregeling Limburg & e52
 
Oosah
OosahOosah
Oosah
 
Skema Bm Kertas2 Set3
Skema Bm Kertas2 Set3Skema Bm Kertas2 Set3
Skema Bm Kertas2 Set3
 
Witch Story
Witch StoryWitch Story
Witch Story
 
Hyperlocal Introduction
Hyperlocal IntroductionHyperlocal Introduction
Hyperlocal Introduction
 
Fazendo Injeção de dependência com Unity 1.2
Fazendo Injeção de dependência com Unity 1.2Fazendo Injeção de dependência com Unity 1.2
Fazendo Injeção de dependência com Unity 1.2
 
Social Network
Social NetworkSocial Network
Social Network
 
merchant.debtum.ru
merchant.debtum.rumerchant.debtum.ru
merchant.debtum.ru
 
3 Secrets Of Productivity
3 Secrets Of Productivity3 Secrets Of Productivity
3 Secrets Of Productivity
 
Most Contagious 2008
Most Contagious 2008Most Contagious 2008
Most Contagious 2008
 
MàQuines I Mecanismes
MàQuines I MecanismesMàQuines I Mecanismes
MàQuines I Mecanismes
 
Univ Aizu week10 about computer
Univ Aizu week10 about  computerUniv Aizu week10 about  computer
Univ Aizu week10 about computer
 
Fontys business model generation & dichtbij
Fontys business model generation & dichtbijFontys business model generation & dichtbij
Fontys business model generation & dichtbij
 
Пожизненное обучение: критика больших данных в образовании
Пожизненное обучение: критика больших данных в образованииПожизненное обучение: критика больших данных в образовании
Пожизненное обучение: критика больших данных в образовании
 
The Crossroads of dichtbij.nl
The Crossroads of dichtbij.nlThe Crossroads of dichtbij.nl
The Crossroads of dichtbij.nl
 
Учение и обучение в век равногогики
Учение и обучение в век равногогикиУчение и обучение в век равногогики
Учение и обучение в век равногогики
 
Kbh On-Train Media Case Study
Kbh On-Train Media Case StudyKbh On-Train Media Case Study
Kbh On-Train Media Case Study
 
MàQuines I Mecanismes
MàQuines I MecanismesMàQuines I Mecanismes
MàQuines I Mecanismes
 

Ähnlich wie Programação assíncrona com C# 5

TDC 2015 - Execução em Background e Live Tiles em Universal Apps
TDC 2015 - Execução em Background e Live Tiles em Universal AppsTDC 2015 - Execução em Background e Live Tiles em Universal Apps
TDC 2015 - Execução em Background e Live Tiles em Universal AppsDiego Castro
 
Minicurso de PHP Com Ajax
Minicurso de PHP Com AjaxMinicurso de PHP Com Ajax
Minicurso de PHP Com AjaxAdler Medrado
 
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo Silveira
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo SilveiraServlets 3: o contexto assíncrono - JavaOne 2010 - Paulo Silveira
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo SilveiraCaelum
 
TDC 2014 SP - E o DeltaSpike ?
TDC 2014 SP - E o DeltaSpike ?TDC 2014 SP - E o DeltaSpike ?
TDC 2014 SP - E o DeltaSpike ?Rafael Benevides
 
DevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webappsDevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webappsSuissa
 
PDC - Engenharia - Plataforma Microsoft .NET
PDC - Engenharia - Plataforma Microsoft .NETPDC - Engenharia - Plataforma Microsoft .NET
PDC - Engenharia - Plataforma Microsoft .NETslides_teltools
 
Threads tasks e o tal do thread pool
Threads tasks e o tal do thread poolThreads tasks e o tal do thread pool
Threads tasks e o tal do thread poolFabrício Rissetto
 
Mini Curso de jQuery Lambda3/Globalcode
Mini Curso de jQuery Lambda3/GlobalcodeMini Curso de jQuery Lambda3/Globalcode
Mini Curso de jQuery Lambda3/GlobalcodeVictor Cavalcante
 
Programação Multiplataforma em Ambiente Web
Programação Multiplataforma em Ambiente WebProgramação Multiplataforma em Ambiente Web
Programação Multiplataforma em Ambiente WebIsrael Messias
 
Programação para Web II: NodeJS
Programação para Web II:  NodeJSProgramação para Web II:  NodeJS
Programação para Web II: NodeJSAlex Camargo
 
A explosão do Node.js: JavaScript é o novo preto
A explosão do Node.js: JavaScript é o novo pretoA explosão do Node.js: JavaScript é o novo preto
A explosão do Node.js: JavaScript é o novo pretoNando Vieira
 
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...Arquitetura executável: Documentando e automatizando a comunicação da equipe ...
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...WeOp - The Operations Summit
 
Node.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasNode.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasRodrigo Branas
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3David Ruiz
 
PyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonPyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonBruno Rocha
 

Ähnlich wie Programação assíncrona com C# 5 (20)

Comtec 2012 - C# Async
Comtec 2012 - C# AsyncComtec 2012 - C# Async
Comtec 2012 - C# Async
 
TDC 2015 - Execução em Background e Live Tiles em Universal Apps
TDC 2015 - Execução em Background e Live Tiles em Universal AppsTDC 2015 - Execução em Background e Live Tiles em Universal Apps
TDC 2015 - Execução em Background e Live Tiles em Universal Apps
 
Minicurso de PHP Com Ajax
Minicurso de PHP Com AjaxMinicurso de PHP Com Ajax
Minicurso de PHP Com Ajax
 
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo Silveira
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo SilveiraServlets 3: o contexto assíncrono - JavaOne 2010 - Paulo Silveira
Servlets 3: o contexto assíncrono - JavaOne 2010 - Paulo Silveira
 
TDC 2014 SP - E o DeltaSpike ?
TDC 2014 SP - E o DeltaSpike ?TDC 2014 SP - E o DeltaSpike ?
TDC 2014 SP - E o DeltaSpike ?
 
DevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webappsDevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webapps
 
PDC - Engenharia - Plataforma Microsoft .NET
PDC - Engenharia - Plataforma Microsoft .NETPDC - Engenharia - Plataforma Microsoft .NET
PDC - Engenharia - Plataforma Microsoft .NET
 
ASP.NET AJAX
ASP.NET AJAXASP.NET AJAX
ASP.NET AJAX
 
Threads tasks e o tal do thread pool
Threads tasks e o tal do thread poolThreads tasks e o tal do thread pool
Threads tasks e o tal do thread pool
 
Utilizando Docker para escalonar aplicações Node.Js
Utilizando Docker para escalonar aplicações Node.JsUtilizando Docker para escalonar aplicações Node.Js
Utilizando Docker para escalonar aplicações Node.Js
 
Mini Curso de jQuery Lambda3/Globalcode
Mini Curso de jQuery Lambda3/GlobalcodeMini Curso de jQuery Lambda3/Globalcode
Mini Curso de jQuery Lambda3/Globalcode
 
Programação Multiplataforma em Ambiente Web
Programação Multiplataforma em Ambiente WebProgramação Multiplataforma em Ambiente Web
Programação Multiplataforma em Ambiente Web
 
Programação para Web II: NodeJS
Programação para Web II:  NodeJSProgramação para Web II:  NodeJS
Programação para Web II: NodeJS
 
Node js - Javascript Server Side
Node js - Javascript Server SideNode js - Javascript Server Side
Node js - Javascript Server Side
 
Conciex 2012
Conciex 2012Conciex 2012
Conciex 2012
 
A explosão do Node.js: JavaScript é o novo preto
A explosão do Node.js: JavaScript é o novo pretoA explosão do Node.js: JavaScript é o novo preto
A explosão do Node.js: JavaScript é o novo preto
 
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...Arquitetura executável: Documentando e automatizando a comunicação da equipe ...
Arquitetura executável: Documentando e automatizando a comunicação da equipe ...
 
Node.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasNode.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo Branas
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3
 
PyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonPyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com Python
 

Mehr von Giovanni Bassi

O que aprendi montando a arquitetura de microsserviços
O que aprendi montando a arquitetura de microsserviçosO que aprendi montando a arquitetura de microsserviços
O que aprendi montando a arquitetura de microsserviçosGiovanni Bassi
 
Analisando dumps de memória de aplicações .NET
Analisando dumps de memória de aplicações .NETAnalisando dumps de memória de aplicações .NET
Analisando dumps de memória de aplicações .NETGiovanni Bassi
 
Async e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraAsync e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraGiovanni Bassi
 
Conhecendo o AKS, o azure container services com kubernetes
Conhecendo o AKS, o azure container services com kubernetesConhecendo o AKS, o azure container services com kubernetes
Conhecendo o AKS, o azure container services com kubernetesGiovanni Bassi
 
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1Novidades do .NET Core 2.1 e do ASP.NET Core 2.1
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1Giovanni Bassi
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8Giovanni Bassi
 
Engenharia ágil de ponta a ponta do clone ao deploy
Engenharia ágil de ponta a ponta do clone ao deployEngenharia ágil de ponta a ponta do clone ao deploy
Engenharia ágil de ponta a ponta do clone ao deployGiovanni Bassi
 
Entrega contínua fica mais fácil com contêineres
Entrega contínua fica mais fácil com contêineresEntrega contínua fica mais fácil com contêineres
Entrega contínua fica mais fácil com contêineresGiovanni Bassi
 
.NET Core, ASP.NET Core e .NET Standard 2
.NET Core, ASP.NET Core e .NET Standard 2.NET Core, ASP.NET Core e .NET Standard 2
.NET Core, ASP.NET Core e .NET Standard 2Giovanni Bassi
 
.NET com contêineres Windows e Linux
.NET com contêineres Windows e Linux.NET com contêineres Windows e Linux
.NET com contêineres Windows e LinuxGiovanni Bassi
 
Async e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraAsync e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraGiovanni Bassi
 
Compartilhando código entre frontend e backend com Node.js
Compartilhando código entre frontend e backend com Node.jsCompartilhando código entre frontend e backend com Node.js
Compartilhando código entre frontend e backend com Node.jsGiovanni Bassi
 
Construindo uma ferramenta CLI multiplataforma com Node.js
Construindo uma ferramenta CLI multiplataforma com Node.jsConstruindo uma ferramenta CLI multiplataforma com Node.js
Construindo uma ferramenta CLI multiplataforma com Node.jsGiovanni Bassi
 
Um mergulho nos containers windows
Um mergulho nos containers windowsUm mergulho nos containers windows
Um mergulho nos containers windowsGiovanni Bassi
 
Por dentro do .NET Core
Por dentro do .NET CorePor dentro do .NET Core
Por dentro do .NET CoreGiovanni Bassi
 
Build e release pipeline com docker
Build e release pipeline com dockerBuild e release pipeline com docker
Build e release pipeline com dockerGiovanni Bassi
 
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...Giovanni Bassi
 

Mehr von Giovanni Bassi (20)

O que aprendi montando a arquitetura de microsserviços
O que aprendi montando a arquitetura de microsserviçosO que aprendi montando a arquitetura de microsserviços
O que aprendi montando a arquitetura de microsserviços
 
Sendo ágil com git
Sendo ágil com gitSendo ágil com git
Sendo ágil com git
 
Analisando dumps de memória de aplicações .NET
Analisando dumps de memória de aplicações .NETAnalisando dumps de memória de aplicações .NET
Analisando dumps de memória de aplicações .NET
 
Novidades do c# 7 e 8
Novidades do c# 7 e 8Novidades do c# 7 e 8
Novidades do c# 7 e 8
 
Async e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraAsync e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agora
 
Conhecendo o AKS, o azure container services com kubernetes
Conhecendo o AKS, o azure container services com kubernetesConhecendo o AKS, o azure container services com kubernetes
Conhecendo o AKS, o azure container services com kubernetes
 
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1Novidades do .NET Core 2.1 e do ASP.NET Core 2.1
Novidades do .NET Core 2.1 e do ASP.NET Core 2.1
 
C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8C#7, 7.1, 7.2, 7.3 e C# 8
C#7, 7.1, 7.2, 7.3 e C# 8
 
Engenharia ágil de ponta a ponta do clone ao deploy
Engenharia ágil de ponta a ponta do clone ao deployEngenharia ágil de ponta a ponta do clone ao deploy
Engenharia ágil de ponta a ponta do clone ao deploy
 
Entrega contínua fica mais fácil com contêineres
Entrega contínua fica mais fácil com contêineresEntrega contínua fica mais fácil com contêineres
Entrega contínua fica mais fácil com contêineres
 
.NET Core, ASP.NET Core e .NET Standard 2
.NET Core, ASP.NET Core e .NET Standard 2.NET Core, ASP.NET Core e .NET Standard 2
.NET Core, ASP.NET Core e .NET Standard 2
 
.NET com contêineres Windows e Linux
.NET com contêineres Windows e Linux.NET com contêineres Windows e Linux
.NET com contêineres Windows e Linux
 
Async e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agoraAsync e await com JavaScript: entenda e use agora
Async e await com JavaScript: entenda e use agora
 
Compartilhando código entre frontend e backend com Node.js
Compartilhando código entre frontend e backend com Node.jsCompartilhando código entre frontend e backend com Node.js
Compartilhando código entre frontend e backend com Node.js
 
Construindo uma ferramenta CLI multiplataforma com Node.js
Construindo uma ferramenta CLI multiplataforma com Node.jsConstruindo uma ferramenta CLI multiplataforma com Node.js
Construindo uma ferramenta CLI multiplataforma com Node.js
 
O Futuro do C#: C#8
O Futuro do C#: C#8O Futuro do C#: C#8
O Futuro do C#: C#8
 
Um mergulho nos containers windows
Um mergulho nos containers windowsUm mergulho nos containers windows
Um mergulho nos containers windows
 
Por dentro do .NET Core
Por dentro do .NET CorePor dentro do .NET Core
Por dentro do .NET Core
 
Build e release pipeline com docker
Build e release pipeline com dockerBuild e release pipeline com docker
Build e release pipeline com docker
 
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...
Release contínuo de um microsserviço com Docker ASP.net core e Azure Containe...
 

Programação assíncrona com C# 5

  • 1. Programação assíncrona com C# 5 Giovanni Bassi giovanni@lambda3.com.br @giovannibassi blog.lambda3.com.br
  • 2. Giovanni Bassi • Trouxe a Scrum.org, PSM e PSD pro Brasil • Palestrante nacional e internacional (gestão, agile, engenharia e arquitetura de software) • Programador • tecnoretorica.com.br, blog.lambda3.com.br, dotnetarchitects.net • Escalador e ciclista • Não gerente
  • 4. Evolução do C# e VB C# 4.0 + VB 10.0 Dinamismo + paridade nas linguagens C# 3.0 + VB 9.0 Language Integrated Query C# 2.0 + VB 8.0 Generics C# 1.0 + VB 7.0 Código gerenciado
  • 6. Tendências • Aplicações cada vez mais conectadas – Mais latência – Mais problemas de responsividade da interface gráfica (IG) – Mais problemas de escalabilidade • Programação assíncrona – Está se tornando a norma em aplicações escaladas e responsivas – APIs que são somente assíncronas, como JavaScript, Silverlight, Windows 8, Windows Phone
  • 7. Evolução do C# e VB C# 5.0 + VB 11.0 Programação assíncrona C# 4.0 + VB 10.0 Dinamismo + paridade nas linguagens C# 3.0 + VB 9.0 Language Integrated Query C# 2.0 + VB 8.0 Generics C# 1.0 + VB 7.0 Código gerenciado
  • 8. O que há de novo? • Programação assíncrona • Programação assíncrona • Atributos de informação de • Atributos de informação de chamada chamada • Iterators
  • 9. Assincronia em poucas palavras • Síncrono  Espero o resultado antes de retonar – string DownloadString(...); • Assíncrono  Retorne agora, chame de volta com o resultado – void DownloadStringAsync(..., Action<string> callback); • Benefícios da assincronia – Responsividade da interface gráfica: libera as threads de IG para interação com o usuário – Escalabilidade do servidor: A thread pode ser reutilizada para outras requisições
  • 10. Síncrono versus Assíncrono var data = DownloadData(...); ProcessData(data); DownloadDataAsync(... , data => { ProcessData(data); });
  • 11. Síncrono versus Assíncrono var data = DownloadData(...); ProcessData(data); DownloadDataAsync(... , data => { ProcessData(data); });
  • 13. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } Mensagens Thread de IG
  • 14. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 15. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 16. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); }
  • 17. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1
  • 18. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2
  • 19. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2
  • 20. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2 
  • 21. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2 
  • 22. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2  
  • 23. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2  
  • 24. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2   
  • 25. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2    
  • 26. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2     
  • 27. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2      
  • 28. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2       
  • 29. Fluxo de controle assíncrono async void DoWorkAsync() { var t1 = ProcessFeedAsync("www.acme.com/rss"); var t2 = ProcessFeedAsync("www.xyznews.com/rss"); await Task.WhenAll(t1, t2); DisplayMessage("Done"); } async Task ProcessFeedAsync(string url) { var text = await DownloadFeedAsync(url); var doc = ParseFeedIntoDoc(text); await SaveDocAsync(doc); ProcessLog.WriteEntry(url); } t1 t2       
  • 30. Como funciona? async Task<XElement> GetRssAsync(string url) { var client = new WebClient(); var task = client.DownloadStringTaskAsync(url); var text = await task; var xml = XElement.Parse(text); return xml; }
  • 31. Como funciona? async Task<XElement> GetRssAsync(string url) { var client = new WebClient(); var task = client.DownloadStringTaskAsync(url); var text = await task; var xml = XElement.Parse(text); return xml; } Task<XElement> GetRssAsync(string url) { var client = new WebClient(); var task = client.DownloadStringTaskAsync(url); return task.ContinueWith(delegate { var text = task.Result; var xml = XElement.Parse(text); return xml; }); }
  • 32.
  • 33. Como funciona? Task<XElement> GetRssAsync(string url) { var $builder = AsyncTaskMethodBuilder<XElement>.Create(); async Task<XElement> $state = 0; var TaskAwaiter<string> $a1; GetRssAsync(string url) { Action $resume = delegate { var client = new try { WebClient(); var task = if ($state == 1) goto L1; client.DownloadStringTaskAsync(url);new WebClient(); var client = var text = await task; task = client.DownloadStringTaskAsync(url); var $a1 = task.GetAwaiter(); var xml = XElement.Parse(text); return xml; if ($a1.IsCompleted) goto L1; } $state = 1; $a1.OnCompleted($resume); return; L1: var text = $a1.GetResult(); var xml = XElement.Parse(text); $builder.SetResult(xml); } catch (Exception $ex) { $builder.SetException($ex); } }; $resume(); return $builder.Task; }
  • 34. Como funciona? Task<XElement> GetRssAsync(string url) { var $builder = AsyncTaskMethodBuilder<XElement>.Create(); async Task<XElement> $state = 0; var TaskAwaiter<string> $a1; GetRssAsync(string url) { Action $resume = delegate { var client = new try { WebClient(); var task = if ($state == 1) goto L1; client.DownloadStringTaskAsync(url);new WebClient(); var client = var text = await task; task = client.DownloadStringTaskAsync(url); var $a1 = task.GetAwaiter(); var xml = XElement.Parse(text); return xml; if ($a1.IsCompleted) goto L1; } $state = 1; $a1.OnCompleted($resume); return; L1: var text = $a1.GetResult(); var xml = XElement.Parse(text); $builder.SetResult(xml); } catch (Exception $ex) { $builder.SetException($ex); } }; $resume(); return $builder.Task; }
  • 35. Como funciona? Task<XElement> GetRssAsync(string url) { var $builder = AsyncTaskMethodBuilder<XElement>.Create(); async Task<XElement> $state = 0; var TaskAwaiter<string> $a1; GetRssAsync(string url) { Action $resume = delegate { var client = new try { WebClient(); var task = if ($state == 1) goto L1; client.DownloadStringTaskAsync(url);new WebClient(); var client = var text = await task; task = client.DownloadStringTaskAsync(url); var $a1 = task.GetAwaiter(); var xml = XElement.Parse(text); return xml; if ($a1.IsCompleted) goto L1; } $state = 1; $a1.OnCompleted($resume); return; L1: var text = $a1.GetResult(); var xml = XElement.Parse(text); $builder.SetResult(xml); } catch (Exception $ex) { $builder.SetException($ex); } }; $resume(); return $builder.Task; }
  • 36. Como funciona? Task<XElement> GetRssAsync(string url) { var $builder = AsyncTaskMethodBuilder<XElement>.Create(); async Task<XElement> $state = 0; var TaskAwaiter<string> $a1; GetRssAsync(string url) { Action $resume = delegate { var client = new try { WebClient(); var task = if ($state == 1) goto L1; client.DownloadStringTaskAsync(url);new WebClient(); var client = var text = await task; task = client.DownloadStringTaskAsync(url); var $a1 = task.GetAwaiter(); var xml = XElement.Parse(text); return xml; if ($a1.IsCompleted) goto L1; } $state = 1; $a1.OnCompleted($resume); return; L1: var text = $a1.GetResult(); var xml = XElement.Parse(text); $builder.SetResult(xml); } catch (Exception $ex) { $builder.SetException($ex); } }; $resume(); return $builder.Task; }
  • 37. Métodos assíncronos... • São marcados com o novo modificador “async” • Devem retornar void, Task ou Task<T> • Usam o operador “await” para devolver controle cooperativamente • Voltam a ser executados quando uma operação que estava em espera (await) conclui • Podem esperar (await) qualquer coisa que implemente o “padrão de espera” • Executam no contexto de sincronização de quem os chamou • Permitem composição com as construções normais de programação • Parecem com código normal e síncrono!
  • 39. Async com ASP.NET ontem public void AcaoAsync() { AsyncManager.OutstandingOperations.Increment(5); var svc = new AsyncPatternSvc.Service1Client(); AsyncManager.Parameters["textoFinal"] = ""; svc.GetDataCompleted += (sender, args) => { AsyncManager.Parameters["textoFinal"] = ((string)AsyncManager.Parameters["textoFinal"]) + args.Result + ", "; AsyncManager.OutstandingOperations.Decrement(); }; for (int i = 0; i < 5; i++) svc.GetDataAsync(i); } public ActionResult AcaoCompleted(string textoFinal) { return View("RetornoServico", new AsyncModel { Resultado = textoFinal }); }
  • 40. Async com ASP.NET hoje public async Task<ActionResult> Acao() { var svc = new TaskSvc.Service1Client(); var resultados = await Task.WhenAll( from i in Enumerable.Range(0, 5) select svc.GetDataAsync(i)); var textoFinal = string.Join(", ", resultados); return View("RetornoServico", new AsyncModel{ Resultado = textoFinal }); }
  • 41. Suporte no .NET Framework Outras… Windows Presentation ASP.NET Foundation
  • 43. Escalabilidade: Evitando novas threads • Blocos síncronos lógicos esperando por requisições de rede: var feeds = (from url in urls select client.DownloadFeed(url)).ToArray(); var feeds = await Task.WhenAll(from url in urls select client.DownloadFeedAsync(url)); Sem novas threads!
  • 44. Unificando a assincronia • Um cenário assíncrono – Busca alguns links de vídeo no YouTube – Baixa dois vídeos ao mesmo tempo – Cria um novo vídeo a partir dos vídeos baixados – Salva o vídeo resultante
  • 45. Unificando a assincronia try { string[] videoUrls = await ScrapeYoutubeAsync(url); // Rede Task<Video> t1 = DownloadVideoAsync(videoUrls[0]); // Baixe 2 videos Task<Video> t2 = DownloadVideoAsync(videoUrls[1]); Video[] vids = await Task.WhenAll(t1, t2); // Espere os 2 Video v = await MashupVideosAsync(vids[0], vids[1]); // CPU await v.SaveAsync(textbox.Text); // Entrada/Saída } catch (WebException ex) { ReportError(ex); }
  • 46. Métodos assíncronos • (Quase) tão simples quanto código síncrono • Unifica assincronia computacional, de rede e de E/S • Permite servidores mais escaláveis • IG mais responsiva
  • 47. Obrigado! Giovanni Bassi giovanni@lambda3.com.br @giovannibassi blog.lambda3.com.br