SlideShare una empresa de Scribd logo
1 de 34
What’s New In C# 5.0
Paulo Morgado
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
Synchronous UI Application
Synchronous UI Application
private void
HandleLoadButtonClick(object
sender, EventArgs e)
{
try
{
this.loadButton.Visible =
false;
this.progressBar.Visible =
true;
this.pictureBox.Image =
null;
var image =
this.LoadImage();
this.pictureBox.Image =
image;
}
catch (Exception ex)
{
// ...
}
finally
{
this.loadButton.Visible =
true;
this.progressBar.Visible =
false;
}
}
private Image LoadImage()
{
var imageBytes = new
WebClient().DownloadData(Settings.
Default.ImageUrl);
var image =
Bitmap.FromStream(new
MemoryStream(imageBytes));
return image;
}
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
Add the async & await keywords
private async void
HandleLoadButtonClick(object sender,
EventArgs e)
{
try
{
this.loadButton.Visible = false;
this.progressBar.Visible = true;
this.pictureBox.Image = null;
var image = await
this.LoadImageAsync();
this.pictureBox.Image = image;
}
catch (Exception ex)
{
// ...
}
finally
{
this.loadButton.Visible = true;
this.progressBar.Visible = false;
}
}
private async Task<Image> LoadImageAsync()
{
var imageBytes = await new WebClient()
.DownloadDataTaskAsync(Settings.Default.Image
Url);
var image = Bitmap.FromStream(new
MemoryStream(imageBytes));
return image;
}
Introducing Async
async void Button_Click(...)
{
await LoadImageAsync();
UpdateView();
}
async Task LoadImageAsync()
{
// ...
await DownloadRemoteDataAsync(...);
// ...
}
Messagepump
void LoadImage()
{
// ...
DownloadRemoteData(...);
// ...
}
void Button_Click(...)
{
LoadImage();
UpdateView();
}
Click
Introducing 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
Async UI app: deadlock
private void
HandleLoadButtonClick(object sender,
EventArgs e)
{
try
{
this.loadButton.Visible =
false;
this.progressBar.Visible =
true;
this.pictureBox.Image = null;
var image =
this.LoadImageAsync()
.Result;
this.pictureBox.Image = image;
}
catch (Exception ex)
{
// ...
}
finally
{
this.loadButton.Visible = true;
this.progressBar.Visible =
false;
}
}
private async Task<Image>
LoadImageAsync()
{
var imageBytes = await new
WebClient()
.DownloadDataTaskAsync(Settings.Default
.ImageUrl);
var image = Bitmap.FromStream(new
MemoryStream(imageBytes));
return image;
}
Demo
Async with cancelation
Async with cancelation
private async void HandleLoadButtonClick(object
sender, EventArgs e)
{
try
{
this.loadButton.Visible = false;
this.progressBar.Visible = true;
this.cancelButton.Visible = true;
this.pictureBox.Image = null;
var a = SynchronizationContext.Current;
var image = await this.LoadImageAsync();
var b = SynchronizationContext.Current;
this.pictureBox.Image = image;
}
catch (Exception ex)
{
// ...
}
finally
{
this.loadButton.Visible = true;
this.progressBar.Visible = false;
this.cancelButton.Visible = false;
}
}
private async Task<Image> LoadImageAsync()
{
Image image = null;
var a = SynchronizationContext.Current;
try
{
this.cancelationTokenSource = new
CancellationTokenSource();
var imageResponse = await new
HttpClient()
.GetAsync(Settings.Default.ImageUrl,
cancelationTokenSource.Token)
.ConfigureAwait(false);
var x = SynchronizationContext.Current;
if (imageResponse != null)
{
var imageStream = await
imageResponse.Content
.ReadAsStreamAsync();
var c =
SynchronizationContext.Current;
image =
Bitmap.FromStream(imageStream);
}
}
catch (TaskCanceledException ex)
{
}
var b = SynchronizationContext.Current;
return image;
}
private CancellationTokenSource
cancelationTokenSource;
private void HandleCancelButtonClick(object
sender, EventArgs e)
{
if (this.cancelationTokenSource != null)
{
this.cancelationTokenSource.Cancel();
this.cancelationTokenSource.Dispose();
this.cancelationTokenSource = null;
}
}
Demo
Async console app
Async console app
class Program
{
static void Main(string[] args)
{
Run().Wait();
}
static async Task Run()
{
await Task.Yield();
}
}
Demo
Async unit tests
Async unit tests
[TestMethod]
public async Task TestMethod1()
{
await Task.Delay(5000);
Assert.Fail();
}
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
Resources
• Task-based Asynchronous Pattern
– http://msdn.microsoft.com/library/hh191443.aspx
• 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://ericlippert.com/
– http://blogs.msdn.com/b/ericlippert/archive/tags/c_2300_+5-0/async/
Resources
• 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/
• What’s new in C#5? – Red Gate
– http://www.youtube.com/watch?v=z7nry67oeKc
• Novidades Do C# 5.0 – Comunidade NetPonto
– http://www.youtube.com/watch?v=7Tl6CHf86z4
• Sample Code
– http://code.msdn.microsoft.com/C-50-AsyncAwait-Demo-Code-334679a5
Resources
• Paulo Morgado
– @PauloMorgado
– 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%5B
0%5D.Value=Paulo%20Morgado
– http://www.codeplex.com/UserAccount/UserProfile.aspx?UserName=Paul
oMorgado
– http://www.slideshare.net/PauloJorgeMorgado
Q & A
Thank You!

Más contenido relacionado

La actualidad más candente

CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
koji lin
 

La actualidad más candente (20)

Completable future
Completable futureCompletable future
Completable future
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Sony C#/.NET component set analysis
Sony C#/.NET component set analysisSony C#/.NET component set analysis
Sony C#/.NET component set analysis
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practices
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
Gerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRxGerenciamento de estado no Angular com NgRx
Gerenciamento de estado no Angular com NgRx
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
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
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
Backday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkitBackday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkit
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
 
PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio team is about to produce a technical breakthrough, but for now let...
PVS-Studio team is about to produce a technical breakthrough, but for now let...
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 

Similar a Paulo morgado what's new in c# 5.0

Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
bhochhi
 

Similar a Paulo morgado what's new in c# 5.0 (20)

Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 
React & The Art of Managing Complexity
React &  The Art of Managing ComplexityReact &  The Art of Managing Complexity
React & The Art of Managing Complexity
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
 
Virtual events in C#: something went wrong
Virtual events in C#: something went wrongVirtual events in C#: something went wrong
Virtual events in C#: something went wrong
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Timelapse: interactive record/replay for the web
Timelapse: interactive record/replay for the webTimelapse: interactive record/replay for the web
Timelapse: interactive record/replay for the web
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Heat up your stack
Heat up your stackHeat up your stack
Heat up your stack
 
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
HTML, not just for desktops: Firefox OS - Congreso Universitario Móvil - 201...
 
Incredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and GeneratorsIncredible Machine with Pipelines and Generators
Incredible Machine with Pipelines and Generators
 

Más de iseltech

Luis gregorio big data
Luis gregorio   big dataLuis gregorio   big data
Luis gregorio big data
iseltech
 
Hugo silva physiological computing
Hugo silva   physiological computingHugo silva   physiological computing
Hugo silva physiological computing
iseltech
 
Hernani mergulhao sessao de encerramento
Hernani mergulhao   sessao de encerramentoHernani mergulhao   sessao de encerramento
Hernani mergulhao sessao de encerramento
iseltech
 
Everis 03 - out systems - um mundo novo
Everis   03 - out systems - um mundo novoEveris   03 - out systems - um mundo novo
Everis 03 - out systems - um mundo novo
iseltech
 
Everis 02 - gestao de identidades e acessos.. o que e
Everis   02 - gestao de identidades e acessos.. o que eEveris   02 - gestao de identidades e acessos.. o que e
Everis 02 - gestao de identidades e acessos.. o que e
iseltech
 
Everis 01 - introdução
Everis   01 - introduçãoEveris   01 - introdução
Everis 01 - introdução
iseltech
 
Carlos costa open source em portugal
Carlos costa   open source em portugalCarlos costa   open source em portugal
Carlos costa open source em portugal
iseltech
 
Tiago fernandes leave your mark
Tiago fernandes   leave your markTiago fernandes   leave your mark
Tiago fernandes leave your mark
iseltech
 
Ricardo almeida business assurance raid
Ricardo almeida   business assurance raidRicardo almeida   business assurance raid
Ricardo almeida business assurance raid
iseltech
 
Reditus business transformation outsourcing
Reditus   business transformation outsourcingReditus   business transformation outsourcing
Reditus business transformation outsourcing
iseltech
 
Quidgest genio
Quidgest   genioQuidgest   genio
Quidgest genio
iseltech
 
Paulo ribeiro o futuro da comunicação entre pessoas e empresas
Paulo ribeiro   o futuro da comunicação entre pessoas e empresasPaulo ribeiro   o futuro da comunicação entre pessoas e empresas
Paulo ribeiro o futuro da comunicação entre pessoas e empresas
iseltech
 
Luis garcia mind the gap
Luis garcia   mind the gapLuis garcia   mind the gap
Luis garcia mind the gap
iseltech
 
Isel formula student
Isel formula studentIsel formula student
Isel formula student
iseltech
 
Accenture technology areas
Accenture   technology areasAccenture   technology areas
Accenture technology areas
iseltech
 
Sergio costa web em realtime
Sergio costa   web em realtimeSergio costa   web em realtime
Sergio costa web em realtime
iseltech
 
Pedro henriques mobile road to success
Pedro henriques   mobile road to successPedro henriques   mobile road to success
Pedro henriques mobile road to success
iseltech
 
Manuel barata sessao de abertura
Manuel barata   sessao de aberturaManuel barata   sessao de abertura
Manuel barata sessao de abertura
iseltech
 
Joao cardoso windows phone nfc
Joao cardoso   windows phone nfcJoao cardoso   windows phone nfc
Joao cardoso windows phone nfc
iseltech
 
Joao cardoso nokia
Joao cardoso   nokiaJoao cardoso   nokia
Joao cardoso nokia
iseltech
 

Más de iseltech (20)

Luis gregorio big data
Luis gregorio   big dataLuis gregorio   big data
Luis gregorio big data
 
Hugo silva physiological computing
Hugo silva   physiological computingHugo silva   physiological computing
Hugo silva physiological computing
 
Hernani mergulhao sessao de encerramento
Hernani mergulhao   sessao de encerramentoHernani mergulhao   sessao de encerramento
Hernani mergulhao sessao de encerramento
 
Everis 03 - out systems - um mundo novo
Everis   03 - out systems - um mundo novoEveris   03 - out systems - um mundo novo
Everis 03 - out systems - um mundo novo
 
Everis 02 - gestao de identidades e acessos.. o que e
Everis   02 - gestao de identidades e acessos.. o que eEveris   02 - gestao de identidades e acessos.. o que e
Everis 02 - gestao de identidades e acessos.. o que e
 
Everis 01 - introdução
Everis   01 - introduçãoEveris   01 - introdução
Everis 01 - introdução
 
Carlos costa open source em portugal
Carlos costa   open source em portugalCarlos costa   open source em portugal
Carlos costa open source em portugal
 
Tiago fernandes leave your mark
Tiago fernandes   leave your markTiago fernandes   leave your mark
Tiago fernandes leave your mark
 
Ricardo almeida business assurance raid
Ricardo almeida   business assurance raidRicardo almeida   business assurance raid
Ricardo almeida business assurance raid
 
Reditus business transformation outsourcing
Reditus   business transformation outsourcingReditus   business transformation outsourcing
Reditus business transformation outsourcing
 
Quidgest genio
Quidgest   genioQuidgest   genio
Quidgest genio
 
Paulo ribeiro o futuro da comunicação entre pessoas e empresas
Paulo ribeiro   o futuro da comunicação entre pessoas e empresasPaulo ribeiro   o futuro da comunicação entre pessoas e empresas
Paulo ribeiro o futuro da comunicação entre pessoas e empresas
 
Luis garcia mind the gap
Luis garcia   mind the gapLuis garcia   mind the gap
Luis garcia mind the gap
 
Isel formula student
Isel formula studentIsel formula student
Isel formula student
 
Accenture technology areas
Accenture   technology areasAccenture   technology areas
Accenture technology areas
 
Sergio costa web em realtime
Sergio costa   web em realtimeSergio costa   web em realtime
Sergio costa web em realtime
 
Pedro henriques mobile road to success
Pedro henriques   mobile road to successPedro henriques   mobile road to success
Pedro henriques mobile road to success
 
Manuel barata sessao de abertura
Manuel barata   sessao de aberturaManuel barata   sessao de abertura
Manuel barata sessao de abertura
 
Joao cardoso windows phone nfc
Joao cardoso   windows phone nfcJoao cardoso   windows phone nfc
Joao cardoso windows phone nfc
 
Joao cardoso nokia
Joao cardoso   nokiaJoao cardoso   nokia
Joao cardoso nokia
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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?
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 

Paulo morgado what's new in c# 5.0

  • 1. What’s New In C# 5.0 Paulo Morgado
  • 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. Synchronous UI Application private void HandleLoadButtonClick(object sender, EventArgs e) { try { this.loadButton.Visible = false; this.progressBar.Visible = true; this.pictureBox.Image = null; var image = this.LoadImage(); this.pictureBox.Image = image; } catch (Exception ex) { // ... } finally { this.loadButton.Visible = true; this.progressBar.Visible = false; } } private Image LoadImage() { var imageBytes = new WebClient().DownloadData(Settings. Default.ImageUrl); var image = Bitmap.FromStream(new MemoryStream(imageBytes)); return image; }
  • 8. Introducing Async - Yesterday Click void LoadImage() { // ... LoadLocalData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click Messagepump
  • 9. Introducing Async - Today Click void LoadImage() { // ... DownloadRemoteData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click Messagepump
  • 10. Demo Add the async & await keywords
  • 11. Add the async & await keywords private async void HandleLoadButtonClick(object sender, EventArgs e) { try { this.loadButton.Visible = false; this.progressBar.Visible = true; this.pictureBox.Image = null; var image = await this.LoadImageAsync(); this.pictureBox.Image = image; } catch (Exception ex) { // ... } finally { this.loadButton.Visible = true; this.progressBar.Visible = false; } } private async Task<Image> LoadImageAsync() { var imageBytes = await new WebClient() .DownloadDataTaskAsync(Settings.Default.Image Url); var image = Bitmap.FromStream(new MemoryStream(imageBytes)); return image; }
  • 12. Introducing Async async void Button_Click(...) { await LoadImageAsync(); UpdateView(); } async Task LoadImageAsync() { // ... await DownloadRemoteDataAsync(...); // ... } Messagepump void LoadImage() { // ... DownloadRemoteData(...); // ... } void Button_Click(...) { LoadImage(); UpdateView(); } Click
  • 13. Introducing Async Click async Task LoadImageAsync() { // ... await DownloadRemoteDataAsync(...); // ... } async void Button_Click(...) { await LoadImageAsync(); UpdateView(); } Click Messagepump Task ... DownloadRemoteDataAsync Task ... LoadImageAsync Download LoadImage
  • 14. Demo Async UI app: re-entrancy and deadlock
  • 15. Async UI app: deadlock private void HandleLoadButtonClick(object sender, EventArgs e) { try { this.loadButton.Visible = false; this.progressBar.Visible = true; this.pictureBox.Image = null; var image = this.LoadImageAsync() .Result; this.pictureBox.Image = image; } catch (Exception ex) { // ... } finally { this.loadButton.Visible = true; this.progressBar.Visible = false; } } private async Task<Image> LoadImageAsync() { var imageBytes = await new WebClient() .DownloadDataTaskAsync(Settings.Default .ImageUrl); var image = Bitmap.FromStream(new MemoryStream(imageBytes)); return image; }
  • 17. Async with cancelation private async void HandleLoadButtonClick(object sender, EventArgs e) { try { this.loadButton.Visible = false; this.progressBar.Visible = true; this.cancelButton.Visible = true; this.pictureBox.Image = null; var a = SynchronizationContext.Current; var image = await this.LoadImageAsync(); var b = SynchronizationContext.Current; this.pictureBox.Image = image; } catch (Exception ex) { // ... } finally { this.loadButton.Visible = true; this.progressBar.Visible = false; this.cancelButton.Visible = false; } } private async Task<Image> LoadImageAsync() { Image image = null; var a = SynchronizationContext.Current; try { this.cancelationTokenSource = new CancellationTokenSource(); var imageResponse = await new HttpClient() .GetAsync(Settings.Default.ImageUrl, cancelationTokenSource.Token) .ConfigureAwait(false); var x = SynchronizationContext.Current; if (imageResponse != null) { var imageStream = await imageResponse.Content .ReadAsStreamAsync(); var c = SynchronizationContext.Current; image = Bitmap.FromStream(imageStream); } } catch (TaskCanceledException ex) { } var b = SynchronizationContext.Current; return image; } private CancellationTokenSource cancelationTokenSource; private void HandleCancelButtonClick(object sender, EventArgs e) { if (this.cancelationTokenSource != null) { this.cancelationTokenSource.Cancel(); this.cancelationTokenSource.Dispose(); this.cancelationTokenSource = null; } }
  • 19. Async console app class Program { static void Main(string[] args) { Run().Wait(); } static async Task Run() { await Task.Yield(); } }
  • 21. Async unit tests [TestMethod] public async Task TestMethod1() { await Task.Delay(5000); Assert.Fail(); }
  • 23. 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
  • 24. 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)); }
  • 25. 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 = "") { // … }
  • 27. 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
  • 29. 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
  • 30. Resources • Task-based Asynchronous Pattern – http://msdn.microsoft.com/library/hh191443.aspx • 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://ericlippert.com/ – http://blogs.msdn.com/b/ericlippert/archive/tags/c_2300_+5-0/async/
  • 31. Resources • 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/ • What’s new in C#5? – Red Gate – http://www.youtube.com/watch?v=z7nry67oeKc • Novidades Do C# 5.0 – Comunidade NetPonto – http://www.youtube.com/watch?v=7Tl6CHf86z4 • Sample Code – http://code.msdn.microsoft.com/C-50-AsyncAwait-Demo-Code-334679a5
  • 32. Resources • Paulo Morgado – @PauloMorgado – 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%5B 0%5D.Value=Paulo%20Morgado – http://www.codeplex.com/UserAccount/UserProfile.aspx?UserName=Paul oMorgado – http://www.slideshare.net/PauloJorgeMorgado
  • 33. Q & A