SlideShare a Scribd company logo
1 of 29
33ª Reunião Lisboa - 24/11/2012 http://netponto.org
What’s New In C# 5.0?
Paulo Morgado
WHO AM I?
Paulo Morgado
CodePlex
Revista
PROGRAMAR
A LANGUAGE FOR EACH GENERATION
THE EVOLUTION OF C#
C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0
Managed Generics LINQ Dynamic Async
THE EVOLUTION OF C#
C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0
Managed Generics LINQ Dynamic Async
please wait for the next slide
clicking won’t make it come any faster
Demo
• Sync UI app
INTRODUCING ASYNC - YESTERDAY
Click
void LoadImage()
{
// ...
LoadLocalData(...);
// ...
}
void Button_Click(...)
{
LoadImage();
UpdateView();
}
Click
Messagepump
INTRODUCING ASYNC - TODAY
Click
void LoadImage()
{
// ...
DownloadRemoteData(...);
// ...
}
void Button_Click(...)
{
LoadImage();
UpdateView();
}
Click
Messagepump
Demo
• Add the async & await keywords
INTRODUCING ASYNC
async void Button_Click(...)
{
await LoadImageAsync();
UpdateView();
}
async Task LoadImageAsync()
{
// ...
await DownloadRemoteDataAsync(...);
// ...
}
Messagepump
void LoadImage()
{
// ...
DownloadRemoteData(...);
// ...
}
void Button_Click(...)
{
LoadImage();
UpdateView();
}
Click
EXPLAINING ASYNC
Click
async Task LoadImageAsync()
{
// ...
await DownloadRemoteDataAsync(...);
// ...
}
async void Button_Click(...)
{
await LoadImageAsync();
UpdateView();
}
Click
Messagepump
Task ...
DownloadRemoteDataAsync
Task ...
LoadImageAsync
Download
LoadImage
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/
RESOURCES
• Sample code
– http://code.msdn.microsoft.com/C-50-AsyncAwait-Demo-Code-334679a5
• 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
Patrocinador “GOLD”
Twitter: @PTMicrosoft
http://www.microsoft.com/portugal
Patrocinadores “Silver”
Próximas reuniões presenciais
• 24/11/2012 – Novembro (Lisboa)
• 08/12/2012 – Dezembro (Lisboa)
• 26/01/2013 – Janeiro (Lisboa)
23/02/2013 – Fevereiro (Lisboa)
Reserva estes dias na agenda! :)
THANK YOU!
Paulo Morgado
CodePlex
Revista
PROGRAMAR

More Related Content

What's hot

What's hot (18)

Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Learn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator OverloadingLearn C# Programming Polymorphism & Operator Overloading
Learn C# Programming Polymorphism & Operator Overloading
 
GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005GNU Compiler Collection - August 2005
GNU Compiler Collection - August 2005
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
Measuring maintainability; software metrics explained
Measuring maintainability; software metrics explainedMeasuring maintainability; software metrics explained
Measuring maintainability; software metrics explained
 
A tutorial on C++ Programming
A tutorial on C++ ProgrammingA tutorial on C++ Programming
A tutorial on C++ Programming
 
GCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programsGCC Compiler as a Performance Testing tool for C programs
GCC Compiler as a Performance Testing tool for C programs
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
C++
C++C++
C++
 
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.Flowex - Railway Flow-Based Programming with Elixir GenStage.
Flowex - Railway Flow-Based Programming with Elixir GenStage.
 
C++ Chapter 3
C++ Chapter 3C++ Chapter 3
C++ Chapter 3
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#
 

Viewers also liked (7)

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
 
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
 
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# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOutWhat's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOut
 
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
 

Similar to What's new in c# 5.0 net ponto

Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
Satish Verma
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart Frog
Steve Loughran
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
Daniel Egan
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
Saurav Kumar
 

Similar to What's new in c# 5.0 net ponto (20)

As novidades do C# 5.0
As novidades do C# 5.0As novidades do C# 5.0
As novidades do C# 5.0
 
Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flattening
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
LLVM
LLVMLLVM
LLVM
 
Visual Studio .NET2010
Visual Studio .NET2010Visual Studio .NET2010
Visual Studio .NET2010
 
Taming Deployment With Smart Frog
Taming Deployment With Smart FrogTaming Deployment With Smart Frog
Taming Deployment With Smart Frog
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
Refactoring & Restructuring - Improving the Code and Structure of Software
Refactoring & Restructuring - Improving the Code and Structure of SoftwareRefactoring & Restructuring - Improving the Code and Structure of Software
Refactoring & Restructuring - Improving the Code and Structure of Software
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
 
Programming by imitation
Programming by imitationProgramming by imitation
Programming by imitation
 
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for DevelopersMSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
MSDN Presents: Visual Studio 2010, .NET 4, SharePoint 2010 for Developers
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 
Embedded C.pptx
Embedded C.pptxEmbedded C.pptx
Embedded C.pptx
 
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1  Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
Advanced Malware Analysis Training Session 2 - Botnet Analysis Part 1
 
Hot Code Replacement - Alexei Sholik
Hot Code Replacement - Alexei SholikHot Code Replacement - Alexei Sholik
Hot Code Replacement - Alexei Sholik
 
The value of reactive
The value of reactiveThe value of reactive
The value of reactive
 
The Value of Reactive
The Value of ReactiveThe Value of Reactive
The Value of Reactive
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Survey of Program Transformation Technologies
Survey of Program Transformation TechnologiesSurvey of Program Transformation Technologies
Survey of Program Transformation Technologies
 

More from 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
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
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
 

More from Paulo Morgado (8)

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
 
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
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
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
 

Recently uploaded

+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@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
"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 ...
 
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 - 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
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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, ...
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

What's new in c# 5.0 net ponto

  • 1. 33ª Reunião Lisboa - 24/11/2012 http://netponto.org What’s New In C# 5.0? Paulo Morgado
  • 2. WHO AM I? Paulo Morgado CodePlex Revista PROGRAMAR
  • 3. A LANGUAGE FOR EACH GENERATION
  • 4. THE EVOLUTION OF C# C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0 Managed Generics LINQ Dynamic Async
  • 5. THE EVOLUTION OF C# C# 1.0 C# 2.0 C# 3.0 C# 4.0 C# 5.0 Managed Generics LINQ Dynamic Async please wait for the next slide clicking won’t make it come any faster
  • 7. INTRODUCING ASYNC - YESTERDAY Click void LoadImage() { // ... LoadLocalData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click Messagepump
  • 8. INTRODUCING ASYNC - TODAY Click void LoadImage() { // ... DownloadRemoteData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click Messagepump
  • 9. Demo • Add the async & await keywords
  • 10. INTRODUCING ASYNC async void Button_Click(...) { await LoadImageAsync(); UpdateView(); } async Task LoadImageAsync() { // ... await DownloadRemoteDataAsync(...); // ... } Messagepump void LoadImage() { // ... DownloadRemoteData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click
  • 11. EXPLAINING ASYNC Click async Task LoadImageAsync() { // ... await DownloadRemoteDataAsync(...); // ... } async void Button_Click(...) { await LoadImageAsync(); UpdateView(); } Click Messagepump Task ... DownloadRemoteDataAsync Task ... LoadImageAsync Download LoadImage
  • 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. RESOURCES • Sample code – http://code.msdn.microsoft.com/C-50-AsyncAwait-Demo-Code-334679a5 • 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.
  • 28. Próximas reuniões presenciais • 24/11/2012 – Novembro (Lisboa) • 08/12/2012 – Dezembro (Lisboa) • 26/01/2013 – Janeiro (Lisboa) 23/02/2013 – Fevereiro (Lisboa) Reserva estes dias na agenda! :)

Editor's Notes

  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