SlideShare a Scribd company logo
1 of 10
New Asynchronous Pattern
                                                   and
                                              Programming
                                                                             Jan 09, 2013



                                                                                                                        http://www.paxcel.net




                                                                                                   By- Amit Kumar Nigam




                                                                          Paxcel technologies. www.paxcel.net
This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Topics Covered
   Introduction (Async & await)

   Synchronous Block

   Asynchronous Block (new way)

   Control flow in Async program

   Caller Info Attributes in C# 5.0




                                                                                         Paxcel technologies. www.paxcel.net
               This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Introduction
The Asynchronous Programming Model (APM), which has the format
BeginMethodName and EndMethodName.

 The Event based Asynchronous Pattern (EAP), which relies on assigning delegates
to event handlers that will be invoked when an event is triggered.

The Task-based Asynchronous Pattern (TAP), which relies on the Task Parallel
Library (TPL)

    Async and Await, you can use resources in the .NET Framework to create an
asynchronous method as easily as you create a synchronous method.
Asynchronous methods that you define by using async and await are referred to as
async methods.




                                                                                     Paxcel technologies. www.paxcel.net
           This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Synchronous Block

public int AccessTheWeb()
{
  // You need to add a reference to System.Net.Http to declare client.
  HttpClient client = new HttpClient();

    // GetStringAsync returns a string.
    string getString = client.GetString("http://msdn.microsoft.com");

    // You can do other work here
    DoIndependentWork();

    // The return statement specifies an integer result.
    return getStringTask.Length;
}

void DoIndependentWork(){
resultTextBox.Text += "working . . . . . /r/n";
}




                                                                                          Paxcel technologies. www.paxcel.net
                This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Async Block (old way)
const string Feed = "http://google.com";
private void btnaSyncPrev_Click(object sender, RoutedEventArgs e)
{
   StringBuilder builder = new StringBuilder();
   this.AsynchronousCallServerTraditional(builder, 2);
}
public void AsynchronousCallServerTraditional(StringBuilder builder, int i)
{
    if (i > 10)
    {
        MessageBox.Show(
            string.Format("Downloaded Successfully!!! Total Size : {0} chars.",
                    builder.Length));
        return;
     }
     this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i);
     WebClient client = new WebClient();
     client.DownloadStringCompleted += (o,e) =>
     {
         builder.Append(e.Result);
         this.AsynchronousCallServerTraditional(builder, i + 1);
     };

    string currentCall = string.Format(Feed, i);
    client.DownloadStringAsync(new Uri(currentCall), null);

}                                                                                          Paxcel technologies. www.paxcel.net
                 This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Async Block (new way)
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
   // You need to add a reference to System.Net.Http to declare client.
   HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync.
    // - AccessTheWebAsync can't continue until getStringTask is complete.
    // - Meanwhile, control returns to the caller of AccessTheWebAsync.
    // - Control resumes here when getStringTask is complete.
    // - The await operator then retrieves the string result from getStringTask.
    string urlContents = await getStringTask;

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}
                                                                                             Paxcel technologies. www.paxcel.net
                   This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
 The method signature includes an Async or async modifier.
 The name of an async method, by convention, ends with an "Async" suffix.

 The return type is one of the following types:

    I. Task<TResult> if your method has a return statement in which the operand
       has type TResult.
    II. Task if your method has no return statement or has a return statement
            with no operand.
    III. Void (a Sub in Visual Basic) if you're writing an async event handler.
 The method usually includes at least one await expression, which marks a point

where the method can't continue until the awaited asynchronous operation is
complete. In the meantime, the method is suspended, and control returns to the
method's caller.




                                                                                     Paxcel technologies. www.paxcel.net
           This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Async Block (New way)
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>. (See "Return Types" section.)
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
   // You need to add a reference to System.Net.Http to declare client.
   HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync.
    // - AccessTheWebAsync can't continue until getStringTask is complete.
    // - Meanwhile, control returns to the caller of AccessTheWebAsync.
    // - Control resumes here when getStringTask is complete.
    // - The await operator then retrieves the string result from getStringTask.
    string urlContents = await getStringTask;

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}
                                                                                             Paxcel technologies. www.paxcel.net
                   This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
Control flow in Async program




                                                                          Paxcel technologies. www.paxcel.net
This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
class Test
{
static void SayMyName([CallerMemberName] string functionName = "",
              [CallerFilePath] string filePath = "",
              [CallerLineNumber] int lineNumber = 0)
{
     Console.WriteLine("{0}:{1}({2})", filePath, functionName, lineNumber);
}

static void Main(string[ ] args)
{
     SayMyName();
}
}

Output:
c:UsersAmitDocumentsVisual Studio
11Projectstest_consolecstestTest.cs:Main(15)



                                                                                      Paxcel technologies. www.paxcel.net
            This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.

More Related Content

What's hot

Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Modulearjun singh
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0snaniix21_3
 
Spring RTS Engine Checkup
Spring RTS Engine CheckupSpring RTS Engine Checkup
Spring RTS Engine CheckupPVS-Studio
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net coreRajesh Shirsagar
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timingPVS-Studio
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyPVS-Studio
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...PVS-Studio
 
CppCat Static Analyzer Review
CppCat Static Analyzer ReviewCppCat Static Analyzer Review
CppCat Static Analyzer ReviewAndrey Karpov
 
Smalltalk implementation of EXIL, a Component-based Programming Language
 Smalltalk implementation of EXIL, a Component-based Programming Language Smalltalk implementation of EXIL, a Component-based Programming Language
Smalltalk implementation of EXIL, a Component-based Programming LanguageESUG
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerPVS-Studio
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyAndrey Karpov
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Andrey Karpov
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codeAndrey Karpov
 

What's hot (20)

Angular 4 The new Http Client Module
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
 
Sockets in nach0s
Sockets in nach0sSockets in nach0s
Sockets in nach0s
 
Spring RTS Engine Checkup
Spring RTS Engine CheckupSpring RTS Engine Checkup
Spring RTS Engine Checkup
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net core
 
C# Asynchronous delegates
C# Asynchronous delegatesC# Asynchronous delegates
C# Asynchronous delegates
 
An eternal question of timing
An eternal question of timingAn eternal question of timing
An eternal question of timing
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...
 
CppCat Static Analyzer Review
CppCat Static Analyzer ReviewCppCat Static Analyzer Review
CppCat Static Analyzer Review
 
Smalltalk implementation of EXIL, a Component-based Programming Language
 Smalltalk implementation of EXIL, a Component-based Programming Language Smalltalk implementation of EXIL, a Component-based Programming Language
Smalltalk implementation of EXIL, a Component-based Programming Language
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
LoggingBestPractices
LoggingBestPracticesLoggingBestPractices
LoggingBestPractices
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 

Similar to Async pattern

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Rainer Stropek
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
Why async matters
Why async mattersWhy async matters
Why async matterstimbc
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...WebStackAcademy
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
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 DriverMongoDB
 
Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Cristian González
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.liKaran Parikh
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍명신 김
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseindiappsdevelopment
 
Create a custom AutoNumber source
Create a custom AutoNumber sourceCreate a custom AutoNumber source
Create a custom AutoNumber sourcePLM Mechanic .
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19Vivek chan
 

Similar to Async pattern (20)

Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#Workshop: Async and Parallel in C#
Workshop: Async and Parallel in C#
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
Why async matters
Why async mattersWhy async matters
Why async matters
 
Ajax
AjaxAjax
Ajax
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions2 Asp Dot Net Ajax Extensions
2 Asp Dot Net Ajax Extensions
 
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
 
Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1Conociendo el consumo de datos en Windows Phone 8.1
Conociendo el consumo de datos en Windows Phone 8.1
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍동기화 시대를 뛰어넘는 비동기 프로그래밍
동기화 시대를 뛰어넘는 비동기 프로그래밍
 
Android session-5-sajib
Android session-5-sajibAndroid session-5-sajib
Android session-5-sajib
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client library
 
Create a custom AutoNumber source
Create a custom AutoNumber sourceCreate a custom AutoNumber source
Create a custom AutoNumber source
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19
 

More from Paxcel Technologies

Binary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine LearningBinary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine LearningPaxcel Technologies
 
Ssrs 2012(powerview) installation ans configuration
Ssrs 2012(powerview) installation ans configurationSsrs 2012(powerview) installation ans configuration
Ssrs 2012(powerview) installation ans configurationPaxcel Technologies
 
Paxcel Mobile development Portfolio
Paxcel Mobile development PortfolioPaxcel Mobile development Portfolio
Paxcel Mobile development PortfolioPaxcel Technologies
 
Risk Oriented Testing of Web-Based Applications
Risk Oriented Testing of Web-Based ApplicationsRisk Oriented Testing of Web-Based Applications
Risk Oriented Testing of Web-Based ApplicationsPaxcel Technologies
 
Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1Paxcel Technologies
 

More from Paxcel Technologies (11)

Binary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine LearningBinary Class and Multi Class Strategies for Machine Learning
Binary Class and Multi Class Strategies for Machine Learning
 
Window phone 8 introduction
Window phone 8 introductionWindow phone 8 introduction
Window phone 8 introduction
 
Ssrs 2012(powerview) installation ans configuration
Ssrs 2012(powerview) installation ans configurationSsrs 2012(powerview) installation ans configuration
Ssrs 2012(powerview) installation ans configuration
 
Paxcel Mobile development Portfolio
Paxcel Mobile development PortfolioPaxcel Mobile development Portfolio
Paxcel Mobile development Portfolio
 
Sequence diagrams in UML
Sequence diagrams in UMLSequence diagrams in UML
Sequence diagrams in UML
 
Introduction to UML
Introduction to UMLIntroduction to UML
Introduction to UML
 
Risk Oriented Testing of Web-Based Applications
Risk Oriented Testing of Web-Based ApplicationsRisk Oriented Testing of Web-Based Applications
Risk Oriented Testing of Web-Based Applications
 
Knockout.js explained
Knockout.js explainedKnockout.js explained
Knockout.js explained
 
All about Contactless payments
All about Contactless paymentsAll about Contactless payments
All about Contactless payments
 
Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1Html5 deciphered - designing concepts part 1
Html5 deciphered - designing concepts part 1
 
Paxcel Snapshot
Paxcel SnapshotPaxcel Snapshot
Paxcel Snapshot
 

Async pattern

  • 1. New Asynchronous Pattern and Programming Jan 09, 2013 http://www.paxcel.net By- Amit Kumar Nigam Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 2. Topics Covered  Introduction (Async & await)  Synchronous Block  Asynchronous Block (new way)  Control flow in Async program  Caller Info Attributes in C# 5.0 Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 3. Introduction The Asynchronous Programming Model (APM), which has the format BeginMethodName and EndMethodName.  The Event based Asynchronous Pattern (EAP), which relies on assigning delegates to event handlers that will be invoked when an event is triggered. The Task-based Asynchronous Pattern (TAP), which relies on the Task Parallel Library (TPL) Async and Await, you can use resources in the .NET Framework to create an asynchronous method as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods. Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 4. Synchronous Block public int AccessTheWeb() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a string. string getString = client.GetString("http://msdn.microsoft.com"); // You can do other work here DoIndependentWork(); // The return statement specifies an integer result. return getStringTask.Length; } void DoIndependentWork(){ resultTextBox.Text += "working . . . . . /r/n"; } Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 5. Async Block (old way) const string Feed = "http://google.com"; private void btnaSyncPrev_Click(object sender, RoutedEventArgs e) { StringBuilder builder = new StringBuilder(); this.AsynchronousCallServerTraditional(builder, 2); } public void AsynchronousCallServerTraditional(StringBuilder builder, int i) { if (i > 10) { MessageBox.Show( string.Format("Downloaded Successfully!!! Total Size : {0} chars.", builder.Length)); return; } this.tbStatus.Text = string.Format("Calling Server [{0}]..... ", i); WebClient client = new WebClient(); client.DownloadStringCompleted += (o,e) => { builder.Append(e.Result); this.AsynchronousCallServerTraditional(builder, i + 1); }; string currentCall = string.Format(Feed, i); client.DownloadStringAsync(new Uri(currentCall), null); } Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 6. Async Block (new way) // Three things to note in the signature: // - The method has an async modifier. // - The return type is Task or Task<T>. (See "Return Types" section.) // Here, it is Task<int> because the return statement returns an integer. // - The method name ends in "Async." async Task<int> AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task<string>. That means that when you await the // task you'll get a string (urlContents). Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string urlContents = await getStringTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return urlContents.Length; } Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 7.  The method signature includes an Async or async modifier.  The name of an async method, by convention, ends with an "Async" suffix.  The return type is one of the following types: I. Task<TResult> if your method has a return statement in which the operand has type TResult. II. Task if your method has no return statement or has a return statement with no operand. III. Void (a Sub in Visual Basic) if you're writing an async event handler.  The method usually includes at least one await expression, which marks a point where the method can't continue until the awaited asynchronous operation is complete. In the meantime, the method is suspended, and control returns to the method's caller. Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 8. Async Block (New way) // Three things to note in the signature: // - The method has an async modifier. // - The return type is Task or Task<T>. (See "Return Types" section.) // Here, it is Task<int> because the return statement returns an integer. // - The method name ends in "Async." async Task<int> AccessTheWebAsync() { // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task<string>. That means that when you await the // task you'll get a string (urlContents). Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string urlContents = await getStringTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return urlContents.Length; } Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 9. Control flow in Async program Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.
  • 10. class Test { static void SayMyName([CallerMemberName] string functionName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("{0}:{1}({2})", filePath, functionName, lineNumber); } static void Main(string[ ] args) { SayMyName(); } } Output: c:UsersAmitDocumentsVisual Studio 11Projectstest_consolecstestTest.cs:Main(15) Paxcel technologies. www.paxcel.net This is the exclusive property of Paxcel Technologies. This may not be reproduced or given to third parties without their consent.