SlideShare uma empresa Scribd logo
1 de 53
Baixar para ler offline
PROGRAMAÇÃO
CONCORRENTE
EM .NET 4.5


JUAN LOPES
twitter.com/juanplopes
github.com/juanplopes
PROGRAMAÇÃO
TALVEZ CONCORRENTE
EM .NET 4.5


JUAN LOPES
twitter.com/juanplopes
github.com/juanplopes
PROGRAMAÇÃO
ASSÍNCRONA
EM .NET 4.5


JUAN LOPES
twitter.com/juanplopes
github.com/juanplopes
EU PROGRAMO WEB
EU PROGRAMO WEB

POR QUE PROGRAMAR
ASSINCRONAMENTE?
EU PROGRAMO WEB

POR QUE PROGRAMAR
ASSINCRONAMENTE?

   MENOR LATÊNCIA
MAIOR RESPONSIVIDADE
WINDOWS XP
WINDOWS FORMS

NÃO BLOQUEIE A
 THREAD DA UI
WINDOWS 8
    WINRT

NÃO BLOQUEIE A
 THREAD DA UI
I/O vs CPU
I/O vs CPU
I/O É MAIS CARO
I/O vs CPU
I/O É MAIS LENTO
I/O vs CPU
I/O É MAIS LENTO
        DISCO
        REDE
 BANCO DE DADOS
PROGRAMAÇÃO
CONCORRENTE
PROGRAMAÇÃO
CONCORRENTE

  THREADS
PROGRAMAÇÃO
CONCORRENTE

  É DIFÍCIL
PROGRAMAÇÃO
CONCORRENTE

  É DIFÍCIL

  OU NÃO
COMO NÃO FAZER:

new Thread(() =>
{
    //código lento
}).Start();
TALVEZ NÃO PROGRAMAR
 CONCORRENTEMENTE?
TALVEZ NÃO PROGRAMAR
 CONCORRENTEMENTE?

       TALVEZ
  ASSINCRONAMENTE
MAS ANTES,
O QUE TEMOS HOJE?
ATÉ .NET 3.5
BeginInvoke
 EndInvoke
Func<string> ler = () =>
    File.ReadAllText(@"C:test.txt");

var handle = ler.BeginInvoke(null, null);

//qualquer outro código

var resultado = ler.EndInvoke(handle);
var req = WebRequest.Create("http://google.com");
var handle = req.BeginGetRequestStream(null, null);

//qualquer código

var stream = req.EndGetRequestStream(handle);
ATÉ .NET 3.5
Begin[QualquerCoisa]
 End[QualquerCoisa]
ATÉ .NET 3.5
Begin[QualquerCoisa]
 End[QualquerCoisa]

     THREADS
 RACE CONDITIONS
 MAIS COMPLICADO
.NET 4.0
PARALLEL EXTENSIONS

  PLINQ (Parallel LINQ)
            +
TPL (Task Parallel Library)
.NET 4.0
PLINQ (Parallel LINQ)
var files = new[] {"file1.txt", "file2.txt"};

var contents = string.Join("", files
    .AsParallel()
    .Select(File.ReadAllText)
    .ToArray());
.NET 4.0
TPL (Task Parallel Library)
.NET 4.0
TPL (Task Parallel Library)

       Task<T>
var task = Task.Run(() =>
    File.ReadAllText(@"C:test.txt"));

//qualquer outro código

var resultado = task.Result;
.NET 4.0
TPL (Task Parallel Library)

      THREADS
   RACE CONDITIONS
  MENOS COMPLICADO
.NET 4.5
 ASYNC
 AWAIT
fs.readFile('test.txt', function (err, data) {
    if (err) throw err;
    console.log(data);
});
Task.Run(() => File.ReadAllText(@"test.txt"))
    .ContinueWith(x => Console.WriteLine(x.Result));
var task = Task.Run(() => File.ReadAllText(@"test.txt"));

task.ContinueWith(x => Console.WriteLine(x.Result));
var task = Task.Run(() => File.ReadAllText(@"test.txt"));

Console.WriteLine(await task);
static async Task<int> GoogleMaisYahoo()
{
    var http = new HttpClient();
    var google = http.GetStringAsync("http://google.com");
    var yahoo = http.GetStringAsync("http://yahoo.com");
    return (await google).Length + (await yahoo).Length;
}

static void Main(string[] args)
{
    var task = GooglePlusYahoo();

    //qualquer código

    Console.WriteLine(task.Result);
    Console.ReadLine();
}
static Task<int> GooglePlusYahoo()
{
    var http = new HttpClient();
    var google = http.GetStringAsync("http://google.com");
    var yahoo = http.GetStringAsync("http://yahoo.com");
    return Task.WhenAll(google, yahoo)
        .ContinueWith(x =>
            x.Result[0].Length + x.Result[1].Length);
}

static void Main(string[] args)
{
    var task = GooglePlusYahoo();

    //qualquer código

    Console.WriteLine(task.Result);
    Console.ReadLine();
}
.NET 4.5
        ASYNC
        AWAIT

    SEM THREADS
SEM RACE CONDITIONS
MUITO MENOS COMPLICADO
RESOLVE 92.4242% DOS
   PROBLEMAS QUE
 THREADS RESOLVEM,
 APROXIMADAMENTE
private async void button1_Click(object sender, EventArgs e)
{
    var http = new HttpClient();
    page.Text = "Loading...";
    page.Text = await http.GetStringAsync("http://google.com");
}
MESMA THREAD QUE CHAMOU O MÉTODO
                 POTENCIALMENTE NOVA THREAD




private async void button1_Click(object sender, EventArgs e)
{
    var http = new HttpClient();
    page.Text = "Loading...";
    page.Text = await http.GetStringAsync("http://google.com");
}
ENTÃO CONTINUAMOS
   COM THREADS
BLOQUEADAS EM I/O?
ENTÃO CONTINUAMOS
   COM THREADS
BLOQUEADAS EM I/O?

       NÃO
IOCP
IOCP
I/O COMPLETION PORTS

FUNCIONALIDADE DO S.O.
ASYNC "THREADLESS" I/O
NÃO HÁ THREADS
BLOQUEADAS ESPERANDO
   CADA I/O TERMINAR
NÃO HÁ THREADS
BLOQUEADAS ESPERANDO
   CADA I/O TERMINAR
HÁ UMA ÚNICA THREAD DE IO
   QUE LÊ UMA FILA
MÉTODOS DA BCL QUE
TERMINAM COM "ASYNC",
GERALMENTE USAM IOCP
MÉTODOS DA BCL QUE
TERMINAM COM "ASYNC",
GERALMENTE USAM IOCP

 FileStream#ReadAsync
HttpClient#GetStringAsync
    Socket#SendAsync
OBRIGADO!
TWITTER.COM/JUANPLOPES
GITHUB.COM/JUANPLOPES

Mais conteúdo relacionado

Mais procurados

Assurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring frameworkAssurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring framework
Gosuke Miyashita
 

Mais procurados (20)

Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Why async matters
Why async mattersWhy async matters
Why async matters
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutes
 
Process file one after another
Process file one after anotherProcess file one after another
Process file one after another
 
Domains!
Domains!Domains!
Domains!
 
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
JDO 2019: Serverless Hype Driven Development - Grzegorz Piotrowski
 
Implement server push in flask framework
Implement server push in flask frameworkImplement server push in flask framework
Implement server push in flask framework
 
What's new on Laravel 5.5
What's new on Laravel 5.5What's new on Laravel 5.5
What's new on Laravel 5.5
 
Nginx for Fun & Performance - Philipp Krenn - Codemotion Rome 2015
Nginx for Fun & Performance - Philipp Krenn - Codemotion Rome 2015Nginx for Fun & Performance - Philipp Krenn - Codemotion Rome 2015
Nginx for Fun & Performance - Philipp Krenn - Codemotion Rome 2015
 
Sinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящееSinatra: прошлое, будущее и настоящее
Sinatra: прошлое, будущее и настоящее
 
Jones_Lamp_Tutorial
Jones_Lamp_TutorialJones_Lamp_Tutorial
Jones_Lamp_Tutorial
 
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
Christian Strappazzon - Presentazione Python Milano - Codemotion Milano 2017
 
Debugging PHP With Xdebug
Debugging PHP With XdebugDebugging PHP With Xdebug
Debugging PHP With Xdebug
 
Firewall filters
Firewall filtersFirewall filters
Firewall filters
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Push the web with HTML5
Push the web with HTML5Push the web with HTML5
Push the web with HTML5
 
Docker perl build
Docker perl buildDocker perl build
Docker perl build
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
 
Assurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring frameworkAssurer - a pluggable server testing/monitoring framework
Assurer - a pluggable server testing/monitoring framework
 

Destaque (7)

qconsp2015
qconsp2015qconsp2015
qconsp2015
 
qconrio2015
qconrio2015qconrio2015
qconrio2015
 
tdc2012
tdc2012tdc2012
tdc2012
 
uerj201212
uerj201212uerj201212
uerj201212
 
dnarj-20120630
dnarj-20120630dnarj-20120630
dnarj-20120630
 
dnarj20130504
dnarj20130504dnarj20130504
dnarj20130504
 
PIPES: Uma linguagem para processamento distribuído de eventos complexos
PIPES: Uma linguagem para processamento distribuído de eventos complexosPIPES: Uma linguagem para processamento distribuído de eventos complexos
PIPES: Uma linguagem para processamento distribuído de eventos complexos
 

Semelhante a rioinfo2012

Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Priyanka Aash
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
tobiascrawley
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 

Semelhante a rioinfo2012 (20)

About Node.js
About Node.jsAbout Node.js
About Node.js
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Node intro
Node introNode intro
Node intro
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
RichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile DevicesRichFaces - Testing on Mobile Devices
RichFaces - Testing on Mobile Devices
 
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
Breaking Parser Logic: Take Your Path Normalization Off and Pop 0days Out!
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Programming language for the cloud infrastructure
Programming language for the cloud infrastructureProgramming language for the cloud infrastructure
Programming language for the cloud infrastructure
 
201209 tech days .net 4.5 核心功能及綜覽
201209 tech days .net 4.5 核心功能及綜覽201209 tech days .net 4.5 核心功能及綜覽
201209 tech days .net 4.5 核心功能及綜覽
 
Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Developing IT infrastructures with Puppet
Developing IT infrastructures with PuppetDeveloping IT infrastructures with Puppet
Developing IT infrastructures with Puppet
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

rioinfo2012