SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

MVP ShowCast 2013
Programação assíncrona com C# 5
no Visual Studio 2013
Rogério Moraes de Carvalho
Visual C#
Diretor de Tecnologia – VITA Informática
@rogeriomc
rogeriomc.wordpress.com
© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Agenda
♦Padrões assíncronos no .NET Framework 4.5.1
♦Task-based Asynchronous Pattern (TAP)
♦async e await
♦Demonstração 1: TAP, async e await
♦Cancelamento (opcional)
♦Progresso (opcional)
♦Demonstração 2: Cancelamento e progresso

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

.NET 1.0

Padrões assíncronos no
.NET Framework 4.5.1
Asynchronous Programming Model (APM)
Método BeginNomeMetodo
Método EndNomeMetodo

.NET 4.0

.NET 2.0

Event-based Asynchronous Pattern (EAP)
Método NomeMetodoAsync
Evento NomeMetodoCompleted
Opcionalmente um método NomeMetodoAsyncCancel
Opcionalmente um evento NomeMetodoProgressChanged

Task-based Asynchronous Pattern (TAP) *
Método NomeMetodoAsync ou NomeMetodoTaskAsync
* Abordagem atualmente recomendada pela Microsoft para programação assíncrona

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Task-based Asynchronous Pattern (TAP)
♦Padrão baseado nos tipos Task e Task<TResult>
♦ Representam operações assíncronas arbitrarias
♦ Fornecem um ciclo de vida para operações assíncronas
♦ Definidos no namespace System.Threading.Tasks

♦Task helpers
♦ Execução em segundo plano
♦ Task.Run(() => {/* código de segundo plano */})

♦ Composição paralela (combinadores)

♦ Task.WhenAny(params Task[] tasks)
♦ Task.WhenAll(params Task[] tasks)

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Task-based Asynchronous Pattern (TAP)
♦Assinatura da versão síncrona do método
♦ NomeMetodo(...)

♦Assinaturas das versões assíncronas do método

♦ NomeMetodoAsync(...)
♦ NomeMetodoAsync(..., CancellationToken c)
♦ NomeMetodoAsync(..., IProgress<T> p)
♦ NomeMetodoAsync(..., CancellationToken c, IProgress<T> p)

♦Tipos de retorno das versões assíncronas

♦ void NomeMetodo(...)  Task NomeMetodoAsync(...) *
♦ T NomeMetodo(...)  Task<T> NomeMetodoAsync(...)
* Neste caso, a versão assíncrona também pode retornar void

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

async e await
♦Modificador async

♦ Indica que um método, uma expressão lambda ou um método anônimo é
assíncrono

♦Operador await

♦ Suspende uma tarefa (Task ou Task<T>) até que ela seja concluída

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Demonstração 1
TAP, async e await
♦Class Library

♦ Namespace MvpShowCast.Dev.LinguagensProgramacao.Matematica
♦ Classe estática AnaliseCombinatoria
♦ Método estático síncrono: Fatorial(ulong)
♦ Método estático assíncrono: FatorialAsync(ulong)

♦Aplicação WPF (Windows Presentation Foundation)
♦ Consumo do método síncrono
versus
♦ Consumo do método assíncrono

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Cancelamento (opcional)
♦Estrutura CancellationToken *

♦ Propaga a notificação que uma operação deve ser cancelada

♦Classe CancellationTokenSource *

♦ Sinaliza para um CancellationToken que ele deve ser cancelado

* Ambos os tipos estão no namespace System.Threading

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Progresso (opcional)
♦Interface System.IProgress<in T>

♦ Define um fornecedor para atualizações de progresso
♦ Se for null, o progresso não deve ser reportado

♦ Um único método: void Report(T value)

♦Classe System.Progress<T>

♦ Implementa a interface System.IProgress<T>
♦ Permite, opcionalmente, invocar um callback para cada valor de progresso
♦ O evento ProgressChanged permite notificar progressos

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Demonstração 2
Cancelamento e progresso
♦Class Library
♦ Novo método assíncrono:
FatorialAsync(ulong, CancellationToken, IProgress<ulong>)

♦Suporte a cancelamento e progresso na aplicação WPF

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Documentação
♦Task-based Asynchronous Pattern (TAP)
♦ http://msdn.microsoft.com/en-us/library/hh873175.aspx

♦Implementing the Task-based Asynchronous Pattern
♦ http://msdn.microsoft.com/en-us/library/hh873177.aspx

♦Consuming the Task-based Asynchronous Pattern
♦ http://msdn.microsoft.com/en-us/library/hh873173.aspx

♦Asynchronous Programming with Async and Await (C# and Visual
Basic)
♦ http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
SESSÃO: DESENVOLVIMENTO

TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO

Perguntas & Respostas

Rogério Moraes de Carvalho
Visual C#
Diretor de Tecnologia – VITA Informática
@rogeriomc
rogeriom.wordpress.com

© 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.

Contenu connexe

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DEV - Ferramentas de desenvolvimento & Linguagens de programação]

  • 1. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO MVP ShowCast 2013 Programação assíncrona com C# 5 no Visual Studio 2013 Rogério Moraes de Carvalho Visual C# Diretor de Tecnologia – VITA Informática @rogeriomc rogeriomc.wordpress.com © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 2. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Agenda ♦Padrões assíncronos no .NET Framework 4.5.1 ♦Task-based Asynchronous Pattern (TAP) ♦async e await ♦Demonstração 1: TAP, async e await ♦Cancelamento (opcional) ♦Progresso (opcional) ♦Demonstração 2: Cancelamento e progresso © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 3. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO .NET 1.0 Padrões assíncronos no .NET Framework 4.5.1 Asynchronous Programming Model (APM) Método BeginNomeMetodo Método EndNomeMetodo .NET 4.0 .NET 2.0 Event-based Asynchronous Pattern (EAP) Método NomeMetodoAsync Evento NomeMetodoCompleted Opcionalmente um método NomeMetodoAsyncCancel Opcionalmente um evento NomeMetodoProgressChanged Task-based Asynchronous Pattern (TAP) * Método NomeMetodoAsync ou NomeMetodoTaskAsync * Abordagem atualmente recomendada pela Microsoft para programação assíncrona © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 4. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Task-based Asynchronous Pattern (TAP) ♦Padrão baseado nos tipos Task e Task<TResult> ♦ Representam operações assíncronas arbitrarias ♦ Fornecem um ciclo de vida para operações assíncronas ♦ Definidos no namespace System.Threading.Tasks ♦Task helpers ♦ Execução em segundo plano ♦ Task.Run(() => {/* código de segundo plano */}) ♦ Composição paralela (combinadores) ♦ Task.WhenAny(params Task[] tasks) ♦ Task.WhenAll(params Task[] tasks) © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 5. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Task-based Asynchronous Pattern (TAP) ♦Assinatura da versão síncrona do método ♦ NomeMetodo(...) ♦Assinaturas das versões assíncronas do método ♦ NomeMetodoAsync(...) ♦ NomeMetodoAsync(..., CancellationToken c) ♦ NomeMetodoAsync(..., IProgress<T> p) ♦ NomeMetodoAsync(..., CancellationToken c, IProgress<T> p) ♦Tipos de retorno das versões assíncronas ♦ void NomeMetodo(...)  Task NomeMetodoAsync(...) * ♦ T NomeMetodo(...)  Task<T> NomeMetodoAsync(...) * Neste caso, a versão assíncrona também pode retornar void © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 6. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO async e await ♦Modificador async ♦ Indica que um método, uma expressão lambda ou um método anônimo é assíncrono ♦Operador await ♦ Suspende uma tarefa (Task ou Task<T>) até que ela seja concluída © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 7. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Demonstração 1 TAP, async e await ♦Class Library ♦ Namespace MvpShowCast.Dev.LinguagensProgramacao.Matematica ♦ Classe estática AnaliseCombinatoria ♦ Método estático síncrono: Fatorial(ulong) ♦ Método estático assíncrono: FatorialAsync(ulong) ♦Aplicação WPF (Windows Presentation Foundation) ♦ Consumo do método síncrono versus ♦ Consumo do método assíncrono © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 8. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Cancelamento (opcional) ♦Estrutura CancellationToken * ♦ Propaga a notificação que uma operação deve ser cancelada ♦Classe CancellationTokenSource * ♦ Sinaliza para um CancellationToken que ele deve ser cancelado * Ambos os tipos estão no namespace System.Threading © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 9. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Progresso (opcional) ♦Interface System.IProgress<in T> ♦ Define um fornecedor para atualizações de progresso ♦ Se for null, o progresso não deve ser reportado ♦ Um único método: void Report(T value) ♦Classe System.Progress<T> ♦ Implementa a interface System.IProgress<T> ♦ Permite, opcionalmente, invocar um callback para cada valor de progresso ♦ O evento ProgressChanged permite notificar progressos © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 10. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Demonstração 2 Cancelamento e progresso ♦Class Library ♦ Novo método assíncrono: FatorialAsync(ulong, CancellationToken, IProgress<ulong>) ♦Suporte a cancelamento e progresso na aplicação WPF © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 11. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Documentação ♦Task-based Asynchronous Pattern (TAP) ♦ http://msdn.microsoft.com/en-us/library/hh873175.aspx ♦Implementing the Task-based Asynchronous Pattern ♦ http://msdn.microsoft.com/en-us/library/hh873177.aspx ♦Consuming the Task-based Asynchronous Pattern ♦ http://msdn.microsoft.com/en-us/library/hh873173.aspx ♦Asynchronous Programming with Async and Await (C# and Visual Basic) ♦ http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.
  • 12. SESSÃO: DESENVOLVIMENTO TRILHA: FERRAMENTAS DE DESENVOLVIMENTO & LINGUAGENS DE PROGRAMAÇÃO Perguntas & Respostas Rogério Moraes de Carvalho Visual C# Diretor de Tecnologia – VITA Informática @rogeriomc rogeriom.wordpress.com © 2013, MVP ShowCast. Evento organizado por MVPs do Brasil com apoio da Microsoft.