SlideShare uma empresa Scribd logo
1 de 27
What’s New In C# 5.0?
WHO AM I?




Paulo Morgado

    CodePlex


               Revista
               PROGRAMAR
A LANGUAGE FOR EACH GENERATION
THE EVOLUTION OF C#




Managed       Generics       LINQ            Dynamic        Async



     C# 1.0         C# 2.0          C# 3.0         C# 4.0           C# 5.0
THE EVOLUTION OF C#




Managed        Generics        LINQ            Dynamic        Async
                  please wait for the next slide
              clicking won’t make it come any faster
     C# 1.0           C# 2.0          C# 3.0         C# 4.0           C# 5.0
Demo


• Sync UI app
INTRODUCING ASYNC - YESTERDAY



                  Click

               void Button_Click(...)
               {
Message pump




                 LoadImage();
                 UpdateView();
               }                         void LoadImage()
                                         {
                                           // ...
                                           LoadLocalData(...);
                 Click                     // ...
                                         }
INTRODUCING ASYNC - TODAY



                  Click

               void Button_Click(...)
               {
Message pump




                 LoadImage();
                 UpdateView();
               }                        void LoadImage()
                                        {
                                          // ...
                                          DownloadRemoteData(...);
                 Click                    // ...
                                        }
Demo


• Add the async & await keywords
INTRODUCING ASYNC



                   Click

               async void Button_Click(...)
               void Button_Click(...)
               {
Message pump




                 await LoadImageAsync();
                 LoadImage();
                 UpdateView();
               }

                                  async Task LoadImageAsync()
                                  void LoadImage()
                                  {
                                    // ...
                                    await DownloadRemoteDataAsync(...);
                                    DownloadRemoteData(...);
                                    // ...
                                  }
EXPLAINING ASYNC



                   Click

               async void Button_Click(...)
               {
Message pump




                 await LoadImageAsync();
                 UpdateView();
                     TaskLoadImage
                           ...
               }     LoadImageAsync
                                  async Task LoadImageAsync()
                                  {
                  Click             // ...
                                    await DownloadRemoteDataAsync(...);
                                    Task ...
                                    // Download
                                          ...
                                  } DownloadRemoteDataAsync
Demo


• Async UI app: re-entrancy and deadlock
Demo


• Async console app
Demo


• Async unit tests
Source Code Caller ID
SOURCE CODE CALLER ID


• CallerFilePathAttribute
   – Allows you to obtain the full path of the source file that contains the caller.
     This is the file path at the time of compile.
       • http://msdn.microsoft.com/library/system.runtime.compilerservices.callerfilepathattribute.aspx

• CallerLineNumberAttribute
   – Allows you to obtain the line number in the source file at which the method
     is called.
       • http://msdn.microsoft.com/library/system.runtime.compilerservices.callerlinenumberattribute.aspx

• CallerMemberNameAttribute
   – Allows you to obtain the method or property name of the caller to the
     method.
       • http://msdn.microsoft.com/library/system.runtime.compilerservices.callermembernameattribute.aspx
SOURCE CODE CALLER ID - EXAMPLES



static void TraceMessage(
  string message,
  [CallerMemberName] string memberName = "",
  [CallerFilePath] string sourceFilePath = "",
  [CallerLineNumber] int sourceLineNumber = 0)
{
  Trace.WriteLine(
     string.Format(
        "{0} at {1} in {2}:line {3}",
        message,
        memberName,
        sourceFilePath,
        sourceLineNumber));
}
SOURCE CODE CALLER ID - EXAMPLES

private string field;
public string Property
{
  get { return this.field; }
  set
  {
     if (this.field != value)
     {
        this.field = value;
        this.NotifyPropertyChanged();
     }
  }
}

protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
  // …
}
Breaking Changes
BREAKING CHANGES


• You can use the iteration variable of a foreach statement in a
  lambda expression that’s contained in the body of the loop.
• You can use the iteration variable of a foreach statement in a LINQ
  expression that’s contained in the body of the loop.
• Overload resolution has been improved for calls that use named
  arguments to access methods that contain params parameters.
• Overload resolution is improved for calls where the algorithm
  must choose between a Func<object> parameter and a Func
  parameter that has a different type parameter (e.g., string or int?)
  for a Func<dynamic> argument.
• Side effects from named and positional arguments in a method
  call now occur from left to right in the argument list.
         http://msdn.microsoft.com/library/hh678682(v=vs.110).aspx
Resources
RESOURCES


• C# Reference
   – http://msdn.microsoft.com/library/618ayhy6.aspx
• Breaking Changes in C# 5.0
   – http://msdn.microsoft.com/library/hh678682(v=vs.110).aspx
• .NET Framework 4.5
   – http://msdn.microsoft.com/library/vstudio/w0x726c2(v=vs.110).aspx
• Task Parallel Library (TPL)
   – http://msdn.microsoft.com/library/vstudio/dd460717.aspx
• Asynchronous Programming with Async and Await (C# and Visual
  Basic)
   – http://msdn.microsoft.com/library/hh191443.aspx
• Task-based Asynchronous Pattern
   – http://msdn.microsoft.com/library/hh191443.aspx
RESOURCES


• Task.Run vs Task.Factory.StartNew
   – http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
• An Async Premier
   – http://msdn.microsoft.com/vstudio/jj573641.aspx
• Eduasync by Jon Skeet
   – http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx
• Eric Lippert's Blog
   – http://blogs.msdn.com/b/ericlippert/
• Lucian Wischik's Blog
   – http://blogs.msdn.com/b/lucian/archive/tags/async/
• Parallel Programming Team Blog
   – http://blogs.msdn.com/b/pfxteam/archive/tags/async/
RESOURCESO


• Paulo Morgado
   – http://PauloMorgado.NET/
   – http://mvp.support.microsoft.com/profile/Paulo.Morgado
   – http://msmvps.com/blogs/paulomorgado/
   – http://weblogs.asp.net/paulomorgado/
   – http://pontonetpt.org/blogs/paulomorgado/
   – http://www.codeproject.com/Members/PauloMorgado
   – http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=User&f%5B0
     %5D.Value=Paulo%20Morgado
   – http://www.codeplex.com/UserAccount/UserProfile.aspx?UserName=Paulo
     Morgado
Q&A
Thank You
What's New In C# 5.0 - Rumos InsideOut

Mais conteúdo relacionado

Mais procurados

C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
Hadziq Fabroyir
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
Olve Maudal
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
Lei Yu
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
Sidd Singh
 

Mais procurados (20)

C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
Modern C++
Modern C++Modern C++
Modern C++
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
 
C++11
C++11C++11
C++11
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
from java to c
from java to cfrom java to c
from java to c
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Cocoa for Web Developers
Cocoa for Web DevelopersCocoa for Web Developers
Cocoa for Web Developers
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
C++ references
C++ referencesC++ references
C++ references
 

Semelhante a What's New In C# 5.0 - Rumos InsideOut

Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
Max Kleiner
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET Driver
MongoDB
 

Semelhante a What's New In C# 5.0 - Rumos InsideOut (20)

Borland star team to tfs simple migration
Borland star team to tfs simple migrationBorland star team to tfs simple migration
Borland star team to tfs simple migration
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
 
Haxe for Flash Platform developer
Haxe for Flash Platform developerHaxe for Flash Platform developer
Haxe for Flash Platform developer
 
Introduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET DriverIntroduction to the New Asynchronous API in the .NET Driver
Introduction to the New Asynchronous API in the .NET Driver
 
XilinxのxsimでSoftware Driven Verification.pdf
XilinxのxsimでSoftware  Driven Verification.pdfXilinxのxsimでSoftware  Driven Verification.pdf
XilinxのxsimでSoftware Driven Verification.pdf
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Open Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 TutorialOpen Cv 2005 Q4 Tutorial
Open Cv 2005 Q4 Tutorial
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDK
 
C#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webinerC#'ın geleceğine bir bakış webiner
C#'ın geleceğine bir bakış webiner
 
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel AvivSelf Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
 
A Safe Dock for our Programs
A Safe Dock for our ProgramsA Safe Dock for our Programs
A Safe Dock for our Programs
 
Over-the-Air: How we Remotely Compromised the Gateway, BCM, and Autopilot ECU...
Over-the-Air: How we Remotely Compromised the Gateway, BCM, and Autopilot ECU...Over-the-Air: How we Remotely Compromised the Gateway, BCM, and Autopilot ECU...
Over-the-Air: How we Remotely Compromised the Gateway, BCM, and Autopilot ECU...
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32
 
Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?Automatically Assessing Code Understandability: How Far Are We?
Automatically Assessing Code Understandability: How Far Are We?
 
Raising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code QualityRaising the Bar on Robotics Code Quality
Raising the Bar on Robotics Code Quality
 
關於 Puremvc Command 的那點事
關於 Puremvc Command 的那點事關於 Puremvc Command 的那點事
關於 Puremvc Command 的那點事
 
Side effects-con-redux
Side effects-con-reduxSide effects-con-redux
Side effects-con-redux
 
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...Maxim Salnikov - Service Worker: taking the best from the past experience for...
Maxim Salnikov - Service Worker: taking the best from the past experience for...
 

Mais de Paulo Morgado

C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
Paulo Morgado
 
As Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPontoAs Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPonto
Paulo Morgado
 

Mais de Paulo Morgado (15)

NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
 
Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
await Xamarin @ PTXug
await Xamarin @ PTXugawait Xamarin @ PTXug
await Xamarin @ PTXug
 
MVP Showcase 2015 - C#
MVP Showcase 2015 - C#MVP Showcase 2015 - C#
MVP Showcase 2015 - C#
 
Roslyn analyzers: File->New->Project
Roslyn analyzers: File->New->ProjectRoslyn analyzers: File->New->Project
Roslyn analyzers: File->New->Project
 
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
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13
 
What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013
 
What's new in c# 5.0 net ponto
What's new in c# 5.0   net pontoWhat's new in c# 5.0   net ponto
What's new in c# 5.0 net ponto
 
As Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPontoAs Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPonto
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
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
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 

What's New In C# 5.0 - Rumos InsideOut

  • 1. What’s New In C# 5.0?
  • 2. WHO AM I? Paulo Morgado CodePlex Revista PROGRAMAR
  • 3. A LANGUAGE FOR EACH GENERATION
  • 4. THE EVOLUTION OF C# Managed Generics LINQ Dynamic Async C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0
  • 5. THE EVOLUTION OF C# Managed Generics LINQ Dynamic Async please wait for the next slide clicking won’t make it come any faster C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0
  • 7. INTRODUCING ASYNC - YESTERDAY Click void Button_Click(...) { Message pump LoadImage(); UpdateView(); } void LoadImage() { // ... LoadLocalData(...); Click // ... }
  • 8. INTRODUCING ASYNC - TODAY Click void Button_Click(...) { Message pump LoadImage(); UpdateView(); } void LoadImage() { // ... DownloadRemoteData(...); Click // ... }
  • 9. Demo • Add the async & await keywords
  • 10. INTRODUCING ASYNC Click async void Button_Click(...) void Button_Click(...) { Message pump await LoadImageAsync(); LoadImage(); UpdateView(); } async Task LoadImageAsync() void LoadImage() { // ... await DownloadRemoteDataAsync(...); DownloadRemoteData(...); // ... }
  • 11. EXPLAINING ASYNC Click async void Button_Click(...) { Message pump await LoadImageAsync(); UpdateView(); TaskLoadImage ... } LoadImageAsync async Task LoadImageAsync() { Click // ... await DownloadRemoteDataAsync(...); Task ... // Download ... } DownloadRemoteDataAsync
  • 12. Demo • Async UI app: re-entrancy and deadlock
  • 16. SOURCE CODE CALLER ID • CallerFilePathAttribute – Allows you to obtain the full path of the source file that contains the caller. This is the file path at the time of compile. • http://msdn.microsoft.com/library/system.runtime.compilerservices.callerfilepathattribute.aspx • CallerLineNumberAttribute – Allows you to obtain the line number in the source file at which the method is called. • http://msdn.microsoft.com/library/system.runtime.compilerservices.callerlinenumberattribute.aspx • CallerMemberNameAttribute – Allows you to obtain the method or property name of the caller to the method. • http://msdn.microsoft.com/library/system.runtime.compilerservices.callermembernameattribute.aspx
  • 17. SOURCE CODE CALLER ID - EXAMPLES static void TraceMessage( string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Trace.WriteLine( string.Format( "{0} at {1} in {2}:line {3}", message, memberName, sourceFilePath, sourceLineNumber)); }
  • 18. SOURCE CODE CALLER ID - EXAMPLES private string field; public string Property { get { return this.field; } set { if (this.field != value) { this.field = value; this.NotifyPropertyChanged(); } } } protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { // … }
  • 20. BREAKING CHANGES • You can use the iteration variable of a foreach statement in a lambda expression that’s contained in the body of the loop. • You can use the iteration variable of a foreach statement in a LINQ expression that’s contained in the body of the loop. • Overload resolution has been improved for calls that use named arguments to access methods that contain params parameters. • Overload resolution is improved for calls where the algorithm must choose between a Func<object> parameter and a Func parameter that has a different type parameter (e.g., string or int?) for a Func<dynamic> argument. • Side effects from named and positional arguments in a method call now occur from left to right in the argument list. http://msdn.microsoft.com/library/hh678682(v=vs.110).aspx
  • 22. RESOURCES • C# Reference – http://msdn.microsoft.com/library/618ayhy6.aspx • Breaking Changes in C# 5.0 – http://msdn.microsoft.com/library/hh678682(v=vs.110).aspx • .NET Framework 4.5 – http://msdn.microsoft.com/library/vstudio/w0x726c2(v=vs.110).aspx • Task Parallel Library (TPL) – http://msdn.microsoft.com/library/vstudio/dd460717.aspx • Asynchronous Programming with Async and Await (C# and Visual Basic) – http://msdn.microsoft.com/library/hh191443.aspx • Task-based Asynchronous Pattern – http://msdn.microsoft.com/library/hh191443.aspx
  • 23. RESOURCES • Task.Run vs Task.Factory.StartNew – http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx • An Async Premier – http://msdn.microsoft.com/vstudio/jj573641.aspx • Eduasync by Jon Skeet – http://msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx • Eric Lippert's Blog – http://blogs.msdn.com/b/ericlippert/ • Lucian Wischik's Blog – http://blogs.msdn.com/b/lucian/archive/tags/async/ • Parallel Programming Team Blog – http://blogs.msdn.com/b/pfxteam/archive/tags/async/
  • 24. RESOURCESO • Paulo Morgado – http://PauloMorgado.NET/ – http://mvp.support.microsoft.com/profile/Paulo.Morgado – http://msmvps.com/blogs/paulomorgado/ – http://weblogs.asp.net/paulomorgado/ – http://pontonetpt.org/blogs/paulomorgado/ – http://www.codeproject.com/Members/PauloMorgado – http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=User&f%5B0 %5D.Value=Paulo%20Morgado – http://www.codeplex.com/UserAccount/UserProfile.aspx?UserName=Paulo Morgado
  • 25. Q&A

Notas do Editor

  1. Language for each generation* Async is a language feature tailored for the current generation of programs.* Distributed ones. Devices and servers. Communication. Latency.* It’s a new control flow primitive. Like GOTO became GOSUB became function calls.[CLICK]
  2. The Evolution Of C#[CLICK]* C# 1.0 – managed code[CLICK]* C# 2.0 – Generics – anonymous methods, iterators, method variance[CLICK]* C# 3.0 – LINQ – extension methods, anonymous types[CLICK]* C# 4.0 – dynamic programming[CLICK]* C# 5.0 – asynchronous programming[CLICK]
  3. * Oh. That’s not meant to happen.[CLICK]* Leslie Lamport, one of the godfathers of computer science, said “A distributed system is one in which the failure of a computer you didn&apos;t even know existed can render your own computer unusable”.* That’s the messy truth about our generation of programs.[CLICK]* Okay, it looks like we’re okay.
  4. Introducing async: file* You need to understand the message-loop.[CLICK]* It’s a single thread – the UI thread - in an infinite loop, waiting for messages, and handling them.* When button-click arrives, this thread calls into the Button_Click handler.* Oh, I’m giving this talk all in VB, but the feature’s exactly the same in C#.* In this case reading configuration from a text file, and returning.[CLICK]* Then it gets back to the message-loop[CLICK]* and can handle further messages, further UI events.
  5. Introducing async: network* But remember we’re in the distributed generation. Maybe instead of loading config off disk, it gets it off the cloud.[CLICK]* What happens then?[CLICK]* Well, it takes time. And in the meantime, the UI thread can’t handle any other clicks or events or messages.* That’s not a bug. It’s not something we can fix. It’s reality. It’s the speed of light!* (Light might seem fast. But when you add the roundtrips it has to make across the atlantic, and internet backbone router congestion, and TCP algorithm timeouts, well, the milliseconds add up).[CLICK]* Eventually it’ll finish and get to the events. But your application looks poor, especially to mass-market audiences who aren’t used to the spinning toilet bowl of death.
  6. DEMO 1: Add Keywordsin VS11, opening the existing AsyncVB project (in its initial state)DEMO 1: KEYWORDS1. Run itObserve the frozen behavior. Try to e.g. grab it down.Win8 doesn’t even bother with the spinning toilet bowl because it assumes you know better.2. Add Async and Await* IO.Network.DownloadAsync(&quot;http://www.wischik.com/lu/postcards.xml&quot;)* Ctrl+Dot to make method async* Rename it to LoadSettingsAsync:Async Function LoadSettingsAsync() As Task3. Change Button1_Click* Await LoadSettingsAsync()* Ctrl+Dot to make method async: Private Async Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click4. Run itObserve that the button clicks immediately. It still takes time of course due to the speed of light. But everything’s responsive.
  7. Introducing async: recap* Recap what we just did.* Changed it from DownloadRemoteData to “await DownloadRemoteDataAsync”* Change the methodprototype: mark it async, change its name, make it return Task[CLICK]* In the caller, changed it from LoadImage to “Await LoadImageAsync”* Changed the function prototype: marked it async
  8. Introducing async: recap[CLICK CLICKCLICK – speaker is on his/her own at this point! Too complicated to explain in the notes]* By now we have a rough idea of the message-loop. And the fact that continuing after an await all happens via the message loop.* Now let’s see the implications of that.
  9. var image = this.LoadImageAsync(Properties.Settings.Default.ImageUrl).Result;
  10. 1. Invoke it from Main, and manually add Async static void Main(string[] args) {HelloAsync().Wait(); }2. Error: can’t do that. So Wait(). static async void Main(string[] args) { await HelloAsync(); }* Observe: it works fine!* Why? Console apps don&apos;t run on a UI message-loop. They run on the thread pool. That has as many message-loops as it wants. It says “hey, that thar thread over there is blocked, so I’ll just spin up another one.”
  11. using System;using Microsoft.VisualStudio.TestTools.UnitTesting;using System.Threading.Tasks;namespace UnitTests{ [TestClass] public class UnitTest1 { [TestMethod] public async void TestMethod1() { await Task.Delay(1000);Assert.Fail(); } }}
  12. Correctedcompiler bugsChanges to preventexpected bugs withasync