SlideShare uma empresa Scribd logo
1 de 48
Visug

Async in Real Life Applications




                                  1
http://proq.blogspot.com
@GitteTitter
http://www.qframe.be
@qframedotnet

                           2
Overview
• Async
   –   The basics
   –   Exceptions
   –   Cancellation
   –   JS
   –   ...

• In Real Life Applications

• Recommendations

                                 3
.NET: Where are we?
                       C# 5.0 + VB 11.0       Windows Runtime + Async
                                                    Async CTP
                                                    VS11 Beta
                  C# 4.0 + VB 10.0
                                          Dynamic

           C# 3.0 + VB 9.0
                                     Language Integrated Query

     C# 2.0 + VB 8.0
                               Generics

C# 1.0 + VB 7.0
                         Managed Code
                                                                        4
Why Async?
var




var




                   5
Why Async



Fast & Fluid



               6
Can we already do this?
Yes, we can!
                 ... But it’s ugly.
                 ... And hard to do.

 Begin... – End... Method pairs
 Callbacks
                                   7
public IAsyncResult BeginCopyStreamToStream(
                                                                   Stream source, Stream destination, AsyncCallback callback, object state)



                      Can we already do this?
                                                               {
                                                                   var tcs = new TaskCompletionSource<object>(state);
                                                                   if (callback != null) tcs.Task.ContinueWith(_ => callback(tcs.Task));
                                                                   var buffer = new byte[0x1000];

                                                                   Action<IAsyncResult> readWriteLoop = null;
                                                                   readWriteLoop = iar => {
                                                                       try {
                                                                           for (bool isRead = iar == null; ; isRead = !isRead) {
public void CopyStreamToStream(Stream source, Stream destination)              switch (isRead) {
                                                                                   case true:
{                                                                                      iar = source.BeginRead(buffer, 0, buffer.Length,
                                                                                            readResult => {
  byte[] buffer = new byte[0x1000];                                                         if (readResult.CompletedSynchronously) return;
                                                                                            readWriteLoop(readResult);
  int numRead;                                                                         }, null);
                                                                                       if (!iar.CompletedSynchronously) return;
  while ((numRead = source.Read(buffer, 0, buffer.Length)) != 0)                       break;


  {                                                              case false:
                                                                     int numRead = source.EndRead(iar);
                                                                     if (numRead == 0) {
    destination.Write(buffer, 0, numRead);                               tcs.TrySetResult(null);
                                                                         return;
  }                                                                  }
                                                                     iar = destination.BeginWrite(buffer, 0, numRead,
}                                                                        writeResult => {
                                                                                              if (writeResult.CompletedSynchronously) return;
                                                                                              destination.EndWrite(writeResult);
                                                                                              readWriteLoop(null);
                                                                                          }, null);
                                                                                          if (!iar.CompletedSynchronously) return;
                                                                                          destination.EndWrite(iar);
                                                                                          break;
                                                                               }
                                                                           }
                                                                       }
                                                                       catch (Exception e) {
                                                                           tcs.TrySetException(e);
                                                                       }
                                                                   };
                                                                   readWriteLoop(null);
                                                                   return tcs.Task;
                                                               }

                                                               public void EndCopyStreamToStream(IAsyncResult asyncResult) {
                                                                   ((Task)asyncResult).Wait();
                                                               }




                                                                                                                                                8
So, what’s new?


   C# and Visual Basic let you do
asynchronous programming without
             callbacks



                                9
How do we do this?
public void CopyStreamToStream(Stream source, Stream destination)
{
  byte[] buffer = new byte[0x1000];
  int numRead;
  while ((numRead = source.Read(buffer, 0, buffer.Length)) != 0)
  {
    destination.Write(buffer, 0, numRead);
  }
}




public async Task CopyStreamToStreamAsync(Stream source, Stream destination)
{
  byte[] buffer = new byte[0x1000];
  int numRead;
  while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0)
  {
     await destination.WriteAsync(buffer, 0, numRead);
  }
}                                                                              10
What is Async – The Basics




                             11
What is Async – The Basics




                             12
What is Async – The Basics
public async Task<XElement> GetXmlAsync(string url) {
    var client = new HttpClient();
    var response = await client.GetAsync(url);
    var text = response.Content.ReadAsString();
    return XElement.Parse(text);
}


                          public Task<XElement> GetXmlAsync(string url) {
                              var tcs = new TaskCompletionSource<XElement>();
                              var client = new HttpClient();
                              client.GetAsync(url).ContinueWith(task => {
                                  var response = task.Result;
                                  var text = response.Content.ReadAsString();
                                  tcs.SetResult(XElement.Parse(text));
                              });
                              return tcs.Task;
                          }


                                                                          13
DEMO
Some basic async



                   14
So it actually gives me Task or Task<T>

     Yes. With different states.


                                      15
What are those states?




Created   Start       Started   Completed   Completed   Close   Closed
                       Error




                                              Error




                                                                         16
How do we handle errors?
Just use try - catch
try {

   FileOpenPicker p = new FileOpenPicker();
   p.FileTypeFilter.Add(".jpg");

   MyButton.Content =
       (await p.PickSingleFileAsync()).FileName;

} catch(Exception e) {}




                                                   17
DEMO
Exception Handling



                     18
Are there still other states?

 Yes. There is one more.


                                19
What are those states?
                                            Cancelled




                       Cancel



Created   Start       Started   Completed   Completed   Close   Closed
                       Error




                                              Error




                                                                         20
And there’s also a way to
 communicate progress.



                            21
What are those states?
                                            Cancelled




                       Cancel



Created   Start       Started   Completed   Completed   Close   Closed
                       Error




                                              Error




                                                                         22
How do we do this?



await FooAsync(…, cancel, progress);




                                       23
DEMO
Cancellation & Progress



                          24
So, it’s always Task<T>?

   Erm, no, there’s also void
(... And some other types, but we’ll
          get back to those)

                                       25
DEMO
The problem with void



                        26
So what should I do with void then?
async Task          async void
FooAsync(…);        Foo_Click(…);




                                         27
What about those Task methods?
• Yielding control
     await Task.Delay(5000);
     await Task.Yield();

• Background running
     var result = await Task.Run(() => { … work … });

• Parallel composition
     Task first = await Task.WhenAny(task1, task2);
     await Task.WhenAll(task1, task2);


                                                 28
29
Except for those other
      return types that is...

... But I still don’t want to tell you
             about those.

 First let’s ask another question.
                                     30
Are there other languages
     I can use this in?

     Sure there are.

VB                     C++

       JavaScript
                             31
JavaScript Promises
var start = new Date();
Windows.Graphics.Imaging.BitmapDecoder.createAsync(stream)
.then(
    function (decoder) {
        var timeLabel = document.getElementById("TimeLabel");
        timeLabel.innerText = new Date()- start + "ms";
    }
);




                                                          32
DEMO
Async in JavaScript



                      33
Was that a library
I saw you using in that demo?

       Indeed you did.


                                34
I did have to alter some code,
            though...
... And use another return type.



     Task             IAsyncAction
    Task<T>        IAsyncOperation<T>




                                        35
DEMO
Async in a WinMD class library



                                 36
37
To sum up, we have some
recommendations for you.




                           38
TIP 1




Don’t forget to cancel your awaits.




                                      39
TIP 2



  It’s easy to forget
the ‘Async’ extension.




                                 40
TIP 3



   Awaiting a local variable in
JavaScript gives you funky results.



                                      41
TIP 4


  Awaiting a void method reacts
different than awaiting a non-void
             method.




                                      42
TIP 5



Don’t use dialogs in your async
          methods.




                                    43
TIP 6




Don’t await in a catch clause.




                                   44
TIP 7




You end up with a whole lot of async




                                       45
TIP 8

     .Wait, WaitAll
= synchronously waiting

  await, .ContinueWith
= asynchronously waiting


                                   46
47
Let us know what you think

http://proq.blogspot.com
@GitteTitter
http://www.qframe.be
@qframedotnet
info@QFrame.be
gitte.vermeiren@QFrame.be
                                 48

Mais conteúdo relacionado

Mais procurados

Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approachAlexander Granin
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Endless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineEndless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineBodo Tasche
 
Realization of an 8 bit pipelined microprocessor in verilog hdl
Realization of an 8 bit pipelined microprocessor in verilog hdlRealization of an 8 bit pipelined microprocessor in verilog hdl
Realization of an 8 bit pipelined microprocessor in verilog hdlAlexander Decker
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
Boost.Python - domesticating the snake
Boost.Python - domesticating the snakeBoost.Python - domesticating the snake
Boost.Python - domesticating the snakeSławomir Zborowski
 
Go concurrency
Go concurrencyGo concurrency
Go concurrencysiuyin
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196Mahmoud Samir Fayed
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an OverviewRoberto Casadei
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 
Class 24: Imperative Programming
Class 24: Imperative ProgrammingClass 24: Imperative Programming
Class 24: Imperative ProgrammingDavid Evans
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Yoshifumi Kawai
 
Memory Management of C# with Unity Native Collections
Memory Management of C# with Unity Native CollectionsMemory Management of C# with Unity Native Collections
Memory Management of C# with Unity Native CollectionsYoshifumi Kawai
 

Mais procurados (20)

Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
 
Form1.Cs
Form1.CsForm1.Cs
Form1.Cs
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Endless fun with Arduino and Eventmachine
Endless fun with Arduino and EventmachineEndless fun with Arduino and Eventmachine
Endless fun with Arduino and Eventmachine
 
Realization of an 8 bit pipelined microprocessor in verilog hdl
Realization of an 8 bit pipelined microprocessor in verilog hdlRealization of an 8 bit pipelined microprocessor in verilog hdl
Realization of an 8 bit pipelined microprocessor in verilog hdl
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
GoでKVSを書けるのか
GoでKVSを書けるのかGoでKVSを書けるのか
GoでKVSを書けるのか
 
Qt Rest Server
Qt Rest ServerQt Rest Server
Qt Rest Server
 
Boost.Python - domesticating the snake
Boost.Python - domesticating the snakeBoost.Python - domesticating the snake
Boost.Python - domesticating the snake
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
Interpreter, Compiler, JIT from scratch
Interpreter, Compiler, JIT from scratchInterpreter, Compiler, JIT from scratch
Interpreter, Compiler, JIT from scratch
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
Class 24: Imperative Programming
Class 24: Imperative ProgrammingClass 24: Imperative Programming
Class 24: Imperative Programming
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
Memory Management of C# with Unity Native Collections
Memory Management of C# with Unity Native CollectionsMemory Management of C# with Unity Native Collections
Memory Management of C# with Unity Native Collections
 

Destaque

Lesotho presentation
Lesotho presentationLesotho presentation
Lesotho presentationburrou21
 
Lbf innovation zone
Lbf innovation zoneLbf innovation zone
Lbf innovation zoneHotKeyBooks
 
Tu giaidoangiacmo share-book.com
Tu giaidoangiacmo   share-book.comTu giaidoangiacmo   share-book.com
Tu giaidoangiacmo share-book.comDuc Li
 
Phuongphaptangchieucao
PhuongphaptangchieucaoPhuongphaptangchieucao
PhuongphaptangchieucaoDuc Li
 
Спектроскопия рассеяния ионов средних энергий
Спектроскопия рассеяния ионов средних энергийСпектроскопия рассеяния ионов средних энергий
Спектроскопия рассеяния ионов средних энергийshemuhin
 
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)Duc Li
 
Building Cross Platform Mobile Solutions
Building Cross Platform Mobile SolutionsBuilding Cross Platform Mobile Solutions
Building Cross Platform Mobile SolutionsQframe
 
Growing in a Difficult Market
Growing in a Difficult Market Growing in a Difficult Market
Growing in a Difficult Market James Donaldson
 
Document databases
Document databasesDocument databases
Document databasesQframe
 
Community day mvvmcross
Community day mvvmcrossCommunity day mvvmcross
Community day mvvmcrossQframe
 
Traducciones practica en ingles
Traducciones practica en inglesTraducciones practica en ingles
Traducciones practica en inglesKarly Fer
 
Whats new windows phone 8 1
Whats new windows phone 8 1Whats new windows phone 8 1
Whats new windows phone 8 1Qframe
 
Mvvm crossevent basics
Mvvm crossevent basicsMvvm crossevent basics
Mvvm crossevent basicsQframe
 
DDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learnedDDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learnedQframe
 
Corso di Fotografia
Corso di FotografiaCorso di Fotografia
Corso di FotografiaBeppe Fucc
 

Destaque (19)

Google earth
Google earthGoogle earth
Google earth
 
Lesotho presentation
Lesotho presentationLesotho presentation
Lesotho presentation
 
Lbf innovation zone
Lbf innovation zoneLbf innovation zone
Lbf innovation zone
 
Tu giaidoangiacmo share-book.com
Tu giaidoangiacmo   share-book.comTu giaidoangiacmo   share-book.com
Tu giaidoangiacmo share-book.com
 
Phuongphaptangchieucao
PhuongphaptangchieucaoPhuongphaptangchieucao
Phuongphaptangchieucao
 
Спектроскопия рассеяния ионов средних энергий
Спектроскопия рассеяния ионов средних энергийСпектроскопия рассеяния ионов средних энергий
Спектроскопия рассеяния ионов средних энергий
 
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)
Ebook ao thuat doan suy nghi khan gia (ao thuat gia lam nha tien tri)
 
Building Cross Platform Mobile Solutions
Building Cross Platform Mobile SolutionsBuilding Cross Platform Mobile Solutions
Building Cross Platform Mobile Solutions
 
Growing in a Difficult Market
Growing in a Difficult Market Growing in a Difficult Market
Growing in a Difficult Market
 
Document databases
Document databasesDocument databases
Document databases
 
Community day mvvmcross
Community day mvvmcrossCommunity day mvvmcross
Community day mvvmcross
 
Lista solin pintado todo
Lista solin pintado todoLista solin pintado todo
Lista solin pintado todo
 
Quiebra
QuiebraQuiebra
Quiebra
 
Traducciones practica en ingles
Traducciones practica en inglesTraducciones practica en ingles
Traducciones practica en ingles
 
Whats new windows phone 8 1
Whats new windows phone 8 1Whats new windows phone 8 1
Whats new windows phone 8 1
 
Mvvm crossevent basics
Mvvm crossevent basicsMvvm crossevent basics
Mvvm crossevent basics
 
DDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learnedDDD, CQRS, ES lessons learned
DDD, CQRS, ES lessons learned
 
Corso di Fotografia
Corso di FotografiaCorso di Fotografia
Corso di Fotografia
 
Sales forecasting
Sales forecastingSales forecasting
Sales forecasting
 

Semelhante a Visug async

Async Development con Visual Studio 2012
Async Development con Visual Studio 2012Async Development con Visual Studio 2012
Async Development con Visual Studio 2012Raffaele Fanizzi
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETChris Dufour
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing TipsShingo Furuyama
 
write a java program related to Huffman coding.SolutionThe Jav.pdf
write a java program related to Huffman coding.SolutionThe Jav.pdfwrite a java program related to Huffman coding.SolutionThe Jav.pdf
write a java program related to Huffman coding.SolutionThe Jav.pdfjaronkyleigh59760
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programováníPeckaDesign.cz
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2Bahul Neel Upadhyaya
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscexjeffz
 

Semelhante a Visug async (20)

Async Development con Visual Studio 2012
Async Development con Visual Studio 2012Async Development con Visual Studio 2012
Async Development con Visual Studio 2012
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Asynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NETAsynchronous Programming in ASP.NET
Asynchronous Programming in ASP.NET
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing Tips
 
write a java program related to Huffman coding.SolutionThe Jav.pdf
write a java program related to Huffman coding.SolutionThe Jav.pdfwrite a java program related to Huffman coding.SolutionThe Jav.pdf
write a java program related to Huffman coding.SolutionThe Jav.pdf
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
Functional concepts in C#
Functional concepts in C#Functional concepts in C#
Functional concepts in C#
 
Asynchronní programování
Asynchronní programováníAsynchronní programování
Asynchronní programování
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2To Infinity & Beyond: Protocols & sequences in Node - Part 2
To Infinity & Beyond: Protocols & sequences in Node - Part 2
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 

Último

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Último (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Visug async

  • 1. Visug Async in Real Life Applications 1
  • 3. Overview • Async – The basics – Exceptions – Cancellation – JS – ... • In Real Life Applications • Recommendations 3
  • 4. .NET: Where are we? C# 5.0 + VB 11.0 Windows Runtime + Async Async CTP VS11 Beta C# 4.0 + VB 10.0 Dynamic C# 3.0 + VB 9.0 Language Integrated Query C# 2.0 + VB 8.0 Generics C# 1.0 + VB 7.0 Managed Code 4
  • 7. Can we already do this? Yes, we can! ... But it’s ugly. ... And hard to do. Begin... – End... Method pairs Callbacks 7
  • 8. public IAsyncResult BeginCopyStreamToStream( Stream source, Stream destination, AsyncCallback callback, object state) Can we already do this? { var tcs = new TaskCompletionSource<object>(state); if (callback != null) tcs.Task.ContinueWith(_ => callback(tcs.Task)); var buffer = new byte[0x1000]; Action<IAsyncResult> readWriteLoop = null; readWriteLoop = iar => { try { for (bool isRead = iar == null; ; isRead = !isRead) { public void CopyStreamToStream(Stream source, Stream destination) switch (isRead) { case true: { iar = source.BeginRead(buffer, 0, buffer.Length, readResult => { byte[] buffer = new byte[0x1000]; if (readResult.CompletedSynchronously) return; readWriteLoop(readResult); int numRead; }, null); if (!iar.CompletedSynchronously) return; while ((numRead = source.Read(buffer, 0, buffer.Length)) != 0) break; { case false: int numRead = source.EndRead(iar); if (numRead == 0) { destination.Write(buffer, 0, numRead); tcs.TrySetResult(null); return; } } iar = destination.BeginWrite(buffer, 0, numRead, } writeResult => { if (writeResult.CompletedSynchronously) return; destination.EndWrite(writeResult); readWriteLoop(null); }, null); if (!iar.CompletedSynchronously) return; destination.EndWrite(iar); break; } } } catch (Exception e) { tcs.TrySetException(e); } }; readWriteLoop(null); return tcs.Task; } public void EndCopyStreamToStream(IAsyncResult asyncResult) { ((Task)asyncResult).Wait(); } 8
  • 9. So, what’s new? C# and Visual Basic let you do asynchronous programming without callbacks 9
  • 10. How do we do this? public void CopyStreamToStream(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = source.Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, numRead); } } public async Task CopyStreamToStreamAsync(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0) { await destination.WriteAsync(buffer, 0, numRead); } } 10
  • 11. What is Async – The Basics 11
  • 12. What is Async – The Basics 12
  • 13. What is Async – The Basics public async Task<XElement> GetXmlAsync(string url) { var client = new HttpClient(); var response = await client.GetAsync(url); var text = response.Content.ReadAsString(); return XElement.Parse(text); } public Task<XElement> GetXmlAsync(string url) { var tcs = new TaskCompletionSource<XElement>(); var client = new HttpClient(); client.GetAsync(url).ContinueWith(task => { var response = task.Result; var text = response.Content.ReadAsString(); tcs.SetResult(XElement.Parse(text)); }); return tcs.Task; } 13
  • 15. So it actually gives me Task or Task<T> Yes. With different states. 15
  • 16. What are those states? Created Start Started Completed Completed Close Closed Error Error 16
  • 17. How do we handle errors? Just use try - catch try { FileOpenPicker p = new FileOpenPicker(); p.FileTypeFilter.Add(".jpg"); MyButton.Content = (await p.PickSingleFileAsync()).FileName; } catch(Exception e) {} 17
  • 19. Are there still other states? Yes. There is one more. 19
  • 20. What are those states? Cancelled Cancel Created Start Started Completed Completed Close Closed Error Error 20
  • 21. And there’s also a way to communicate progress. 21
  • 22. What are those states? Cancelled Cancel Created Start Started Completed Completed Close Closed Error Error 22
  • 23. How do we do this? await FooAsync(…, cancel, progress); 23
  • 25. So, it’s always Task<T>? Erm, no, there’s also void (... And some other types, but we’ll get back to those) 25
  • 27. So what should I do with void then? async Task async void FooAsync(…); Foo_Click(…); 27
  • 28. What about those Task methods? • Yielding control await Task.Delay(5000); await Task.Yield(); • Background running var result = await Task.Run(() => { … work … }); • Parallel composition Task first = await Task.WhenAny(task1, task2); await Task.WhenAll(task1, task2); 28
  • 29. 29
  • 30. Except for those other return types that is... ... But I still don’t want to tell you about those. First let’s ask another question. 30
  • 31. Are there other languages I can use this in? Sure there are. VB C++ JavaScript 31
  • 32. JavaScript Promises var start = new Date(); Windows.Graphics.Imaging.BitmapDecoder.createAsync(stream) .then( function (decoder) { var timeLabel = document.getElementById("TimeLabel"); timeLabel.innerText = new Date()- start + "ms"; } ); 32
  • 34. Was that a library I saw you using in that demo? Indeed you did. 34
  • 35. I did have to alter some code, though... ... And use another return type. Task IAsyncAction Task<T> IAsyncOperation<T> 35
  • 36. DEMO Async in a WinMD class library 36
  • 37. 37
  • 38. To sum up, we have some recommendations for you. 38
  • 39. TIP 1 Don’t forget to cancel your awaits. 39
  • 40. TIP 2 It’s easy to forget the ‘Async’ extension. 40
  • 41. TIP 3 Awaiting a local variable in JavaScript gives you funky results. 41
  • 42. TIP 4 Awaiting a void method reacts different than awaiting a non-void method. 42
  • 43. TIP 5 Don’t use dialogs in your async methods. 43
  • 44. TIP 6 Don’t await in a catch clause. 44
  • 45. TIP 7 You end up with a whole lot of async 45
  • 46. TIP 8 .Wait, WaitAll = synchronously waiting await, .ContinueWith = asynchronously waiting 46
  • 47. 47
  • 48. Let us know what you think http://proq.blogspot.com @GitteTitter http://www.qframe.be @qframedotnet info@QFrame.be gitte.vermeiren@QFrame.be 48

Notas do Editor

  1. +++ diene callback wordt uitgevoerd op de thread waarhij begonnen is =&gt; NO MORE DISPATCHER.INVOKE !!!!!
  2. Show OnNavigatedTo of PublishHikeAndWaitPoint out:Async and await keywordsTask return typeAsync on a lambdaDrivers are being shown on the map, in the mean time UI stays responsiveHikers are not yet being shown = rest of the method is a callbackI can already click on a driver + second popup = rest of the method is really a callback.
  3. STOP IIS SERVICE !!!In RestCaller en HikerRoute.xaml.csPoint out that:It’s just try-catch