SlideShare a Scribd company logo
1 of 16
Asynchronous Delegates
Overview
•What is Delegate?
•What is Asynchronous Delegate?
•Terms
•BeginInvoke() method
•EndInvoke() method
•IAsyncResult Interface
•AsyncCallback Delegate
•Ways to call methods asynchronously using
BeginInvoke() and EndInvoke()
•Example
•Conclusion
What is Delegate?
•A delegate is a type that represents references to
methods with a particular parameter list and return
type.
•To create an instance of the delegate, one must use a
function that matches that form.
•Unlike function pointers, delegates in C# can call more
than one function
•The methods pointed to by the delegate can be called
synchronously or asynchronously.
What is Asynchronous Delegate?
• When we call a method in an asynchronous way,
the .NET framework obtains a thread from the
thread pool for the method invocation.
• The asynchronous thread can then run the
method in parallel to the calling thread.
• Hence, unlike synchronous methods caller thread
is not blocked
BeginInvoke()
•The BeginInvoke method initiates the asynchronous
call on a separate thread taken from the ThreadPool.
•It consists the same parameters required by the
method (that you want to execute asynchronously) and
consists two additional optional parameters called the
callback parameter and the state parameter.
•BeginInvoke returns a reference to an object
implementing the IAsyncResult interface, which can be
used to monitor the progress of the asynchronous call.
EndInvoke()
•The EndInvoke method retrieves the results of
the asynchronous call and releases the resource
used by the thread.
•The parameters of EndInvoke include the out
and ref parameters of the method that you want
to execute asynchronously, plus a reference to
the IAsyncResult returned by the BeginInvoke().
IAsyncResult & AsyncCallback
•IAsyncResult Interface is used to represent status of an
asynchronous operation.
•The IAsyncResult interface is implemented by classes
containing methods that can operate asynchronously.
•AsyncCallback Delegate is used to reference a method
to be called when a corresponding asynchronous
operation completes.
•The callback method takes IAsyncResult parameter,
which is subsequently used to obtain the results of the
asynchronous operation.
Waiting for an Asynchronous Call with
EndInvoke
•In this scenario, we use BeginInvoke from the Main
thread to call the method, then do some processing on
the main thread and then call EndInvoke().
•Here the EndInvoke() does not return until the
asynchronous call has completed or The main thread
waits till the asynchronous operation is complete.
•This is useful when you want to have the calling thread
to continue processing at the same time the
asynchronous call is executing.
Example
Executing a Callback Method When an
Asynchronous Call Completes
•In this scenario,callback method has been specified in the
call to the BeginInvoke() method, the callback method is
called when the target method ends.
•In the callback method, the EndInvoke() method obtains
the return value and any input/output or output-only
parameters.
•In this pattern, the initial thread initiates the async call but
does not wait or check to see if the thread that was called,
has completed.
•This pattern can be useful if you not want to process the
results of the async call in the main thread.
Example
static void Main()
{ AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
int dummy = 0;
IAsyncResult result = caller.BeginInvoke(3000,
out dummy,
new AsyncCallback(CallbackMethod),
"The call executed on thread {0}, with return value "{1}".");
Console.WriteLine("The main thread {0} continues to execute...",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(4000);
Console.WriteLine("The main thread ends.");
}
static void CallbackMethod(IAsyncResult ar)
{
AsyncResult result = (AsyncResult) ar;
AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate;
string formatString = (string) ar.AsyncState;
int threadId = 0;
string returnValue = caller.EndInvoke(out threadId, ar);
Console.WriteLine(formatString, threadId, returnValue);
Waiting for an Asynchronous Call with
WaitHandle
•In this scenario, the main method calls the method
asynchronously and waits for a WaitHandle before it calls
EndInvoke().
•The WaitHandle is signaled when the asynchronous call
completes, and you can wait for it by calling
the WaitOne method.
•If you use a WaitHandle, you can perform additional
processing before or after the asynchronous call
completes, but before calling EndInvoke to retrieve the
results.
Example
public delegate string MyDelegate(string s);
class Program
{ static void Main(string[] args)
{
MyClass oMyClass = new MyClass();
MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
Console.WriteLine("Going to call the method Asynchronously.");
IAsyncResult IAsyncResult = oMyDelegate.BeginInvoke(“aaaa", null, null);
Console.WriteLine("Back on Main.");
//Wait for the WaitHandle to become signaled.
IAsyncResult.AsyncWaitHandle.WaitOne();
string result = oMyDelegate.EndInvoke(IAsyncResult);
//Close the wait handle.
result.AsyncWaitHandle.Close();
Console.WriteLine(result);
}}
public class MyClass
{ public string MyMethod(string s) {
Thread.Sleep(5000);
return "Hello " + s;
}}
Polling for Asynchronous Call Completion
•In this pattern, the calling thread polls the other thread
(doing async operation) periodically using the IAsyncResult
object and checks whether the thread has completed.
•If not, it continues processing and checks the thread later.
The application does not call EndInvoke() until it knows that
the operation is complete.
•This pattern can be useful when you want your UI to be
responsive, till the async operation completes.
Example
static void Main() {
// The asynchronous method puts the thread id here.
int threadId;
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null);
// Poll while simulating work using IsCompleted Property of IAsyncResult
while(result.IsCompleted == false) {
Thread.Sleep(250);
Console.Write("."); }
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("nThe call executed on thread {0}, with return value
"{1}".",
threadId, returnValue); }}
Summary
• Hence, Asynchronous Delegates can be used
to perform some task while main(caller)
thread is also executing.
• BeginInvoke() and EndInvoke() methods of
the Delegate class are used to call method
asynchronously.
• Four Different ways to call method
asynchronously are: EndInvoke Pattern , Wait
Handle, Polling Pattern, Callback Pattern

More Related Content

What's hot

Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and AggregationDbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and AggregationBIT Durg
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating SystemsRitu Ranjan Shrivastwa
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingguesta40f80
 
Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.Ravi Kumar Patel
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-pptraj732723
 
Design issues of dos
Design issues of dosDesign issues of dos
Design issues of dosvanamali_vanu
 
Operating Systems: Process Scheduling
Operating Systems: Process SchedulingOperating Systems: Process Scheduling
Operating Systems: Process SchedulingDamian T. Gordon
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-threadjavaicon
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
cpu scheduling
cpu schedulingcpu scheduling
cpu schedulinghashim102
 

What's hot (20)

Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and AggregationDbms Notes Lecture 9 : Specialization, Generalization and Aggregation
Dbms Notes Lecture 9 : Specialization, Generalization and Aggregation
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
 
Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.
 
Java threads
Java threadsJava threads
Java threads
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
operating system lecture notes
operating system lecture notesoperating system lecture notes
operating system lecture notes
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt30326851 -operating-system-unit-1-ppt
30326851 -operating-system-unit-1-ppt
 
Design issues of dos
Design issues of dosDesign issues of dos
Design issues of dos
 
Operating Systems: Process Scheduling
Operating Systems: Process SchedulingOperating Systems: Process Scheduling
Operating Systems: Process Scheduling
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
cpu scheduling
cpu schedulingcpu scheduling
cpu scheduling
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Features of java
Features of javaFeatures of java
Features of java
 
Boot process
Boot processBoot process
Boot process
 
Switching
SwitchingSwitching
Switching
 
Applets in java
Applets in javaApplets in java
Applets in java
 

Similar to C# Asynchronous delegates

Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentationahmed sayed
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHarry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaYoung Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and ParallelizationDmitri Nesteruk
 
UVM Driver sequencer handshaking
UVM Driver sequencer handshakingUVM Driver sequencer handshaking
UVM Driver sequencer handshakingHARINATH REDDY
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarXamarin
 
Parallel Programming In Java
Parallel Programming In JavaParallel Programming In Java
Parallel Programming In JavaKnoldus Inc.
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreadingTuan Chau
 

Similar to C# Asynchronous delegates (20)

Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
UVM Driver sequencer handshaking
UVM Driver sequencer handshakingUVM Driver sequencer handshaking
UVM Driver sequencer handshaking
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Parallel Programming In Java
Parallel Programming In JavaParallel Programming In Java
Parallel Programming In Java
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 

More from Prem Kumar Badri

Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexersPrem Kumar Badri
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopePrem Kumar Badri
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and eventsPrem Kumar Badri
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objectsPrem Kumar Badri
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variablesPrem Kumar Badri
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsPrem Kumar Badri
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingPrem Kumar Badri
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsPrem Kumar Badri
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parametersPrem Kumar Badri
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variablesPrem Kumar Badri
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformPrem Kumar Badri
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collectionPrem Kumar Badri
 

More from Prem Kumar Badri (20)

Module 15 attributes
Module 15 attributesModule 15 attributes
Module 15 attributes
 
Module 14 properties and indexers
Module 14 properties and indexersModule 14 properties and indexers
Module 14 properties and indexers
 
Module 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scopeModule 12 aggregation, namespaces, and advanced scope
Module 12 aggregation, namespaces, and advanced scope
 
Module 13 operators, delegates, and events
Module 13 operators, delegates, and eventsModule 13 operators, delegates, and events
Module 13 operators, delegates, and events
 
Module 11 : Inheritance
Module 11 : InheritanceModule 11 : Inheritance
Module 11 : Inheritance
 
Module 10 : creating and destroying objects
Module 10 : creating and destroying objectsModule 10 : creating and destroying objects
Module 10 : creating and destroying objects
 
Module 9 : using reference type variables
Module 9 : using reference type variablesModule 9 : using reference type variables
Module 9 : using reference type variables
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and generics
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Module 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented ProgrammingModule 6 : Essentials of Object Oriented Programming
Module 6 : Essentials of Object Oriented Programming
 
Module 5 : Statements & Exceptions
Module 5 : Statements & ExceptionsModule 5 : Statements & Exceptions
Module 5 : Statements & Exceptions
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Module 3 : using value type variables
Module 3 : using value type variablesModule 3 : using value type variables
Module 3 : using value type variables
 
Module 2: Overview of c#
Module 2:  Overview of c#Module 2:  Overview of c#
Module 2: Overview of c#
 
Module 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET PlatformModule 1 : Overview of the Microsoft .NET Platform
Module 1 : Overview of the Microsoft .NET Platform
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
C# Multi threading
C# Multi threadingC# Multi threading
C# Multi threading
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
C# Generic collections
C# Generic collectionsC# Generic collections
C# Generic collections
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

C# Asynchronous delegates

  • 2. Overview •What is Delegate? •What is Asynchronous Delegate? •Terms •BeginInvoke() method •EndInvoke() method •IAsyncResult Interface •AsyncCallback Delegate •Ways to call methods asynchronously using BeginInvoke() and EndInvoke() •Example •Conclusion
  • 3. What is Delegate? •A delegate is a type that represents references to methods with a particular parameter list and return type. •To create an instance of the delegate, one must use a function that matches that form. •Unlike function pointers, delegates in C# can call more than one function •The methods pointed to by the delegate can be called synchronously or asynchronously.
  • 4. What is Asynchronous Delegate? • When we call a method in an asynchronous way, the .NET framework obtains a thread from the thread pool for the method invocation. • The asynchronous thread can then run the method in parallel to the calling thread. • Hence, unlike synchronous methods caller thread is not blocked
  • 5. BeginInvoke() •The BeginInvoke method initiates the asynchronous call on a separate thread taken from the ThreadPool. •It consists the same parameters required by the method (that you want to execute asynchronously) and consists two additional optional parameters called the callback parameter and the state parameter. •BeginInvoke returns a reference to an object implementing the IAsyncResult interface, which can be used to monitor the progress of the asynchronous call.
  • 6. EndInvoke() •The EndInvoke method retrieves the results of the asynchronous call and releases the resource used by the thread. •The parameters of EndInvoke include the out and ref parameters of the method that you want to execute asynchronously, plus a reference to the IAsyncResult returned by the BeginInvoke().
  • 7. IAsyncResult & AsyncCallback •IAsyncResult Interface is used to represent status of an asynchronous operation. •The IAsyncResult interface is implemented by classes containing methods that can operate asynchronously. •AsyncCallback Delegate is used to reference a method to be called when a corresponding asynchronous operation completes. •The callback method takes IAsyncResult parameter, which is subsequently used to obtain the results of the asynchronous operation.
  • 8. Waiting for an Asynchronous Call with EndInvoke •In this scenario, we use BeginInvoke from the Main thread to call the method, then do some processing on the main thread and then call EndInvoke(). •Here the EndInvoke() does not return until the asynchronous call has completed or The main thread waits till the asynchronous operation is complete. •This is useful when you want to have the calling thread to continue processing at the same time the asynchronous call is executing.
  • 10. Executing a Callback Method When an Asynchronous Call Completes •In this scenario,callback method has been specified in the call to the BeginInvoke() method, the callback method is called when the target method ends. •In the callback method, the EndInvoke() method obtains the return value and any input/output or output-only parameters. •In this pattern, the initial thread initiates the async call but does not wait or check to see if the thread that was called, has completed. •This pattern can be useful if you not want to process the results of the async call in the main thread.
  • 11. Example static void Main() { AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); int dummy = 0; IAsyncResult result = caller.BeginInvoke(3000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value "{1}"."); Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(4000); Console.WriteLine("The main thread ends."); } static void CallbackMethod(IAsyncResult ar) { AsyncResult result = (AsyncResult) ar; AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate; string formatString = (string) ar.AsyncState; int threadId = 0; string returnValue = caller.EndInvoke(out threadId, ar); Console.WriteLine(formatString, threadId, returnValue);
  • 12. Waiting for an Asynchronous Call with WaitHandle •In this scenario, the main method calls the method asynchronously and waits for a WaitHandle before it calls EndInvoke(). •The WaitHandle is signaled when the asynchronous call completes, and you can wait for it by calling the WaitOne method. •If you use a WaitHandle, you can perform additional processing before or after the asynchronous call completes, but before calling EndInvoke to retrieve the results.
  • 13. Example public delegate string MyDelegate(string s); class Program { static void Main(string[] args) { MyClass oMyClass = new MyClass(); MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod); Console.WriteLine("Going to call the method Asynchronously."); IAsyncResult IAsyncResult = oMyDelegate.BeginInvoke(“aaaa", null, null); Console.WriteLine("Back on Main."); //Wait for the WaitHandle to become signaled. IAsyncResult.AsyncWaitHandle.WaitOne(); string result = oMyDelegate.EndInvoke(IAsyncResult); //Close the wait handle. result.AsyncWaitHandle.Close(); Console.WriteLine(result); }} public class MyClass { public string MyMethod(string s) { Thread.Sleep(5000); return "Hello " + s; }}
  • 14. Polling for Asynchronous Call Completion •In this pattern, the calling thread polls the other thread (doing async operation) periodically using the IAsyncResult object and checks whether the thread has completed. •If not, it continues processing and checks the thread later. The application does not call EndInvoke() until it knows that the operation is complete. •This pattern can be useful when you want your UI to be responsive, till the async operation completes.
  • 15. Example static void Main() { // The asynchronous method puts the thread id here. int threadId; AsyncDemo ad = new AsyncDemo(); // Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); // Poll while simulating work using IsCompleted Property of IAsyncResult while(result.IsCompleted == false) { Thread.Sleep(250); Console.Write("."); } // Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("nThe call executed on thread {0}, with return value "{1}".", threadId, returnValue); }}
  • 16. Summary • Hence, Asynchronous Delegates can be used to perform some task while main(caller) thread is also executing. • BeginInvoke() and EndInvoke() methods of the Delegate class are used to call method asynchronously. • Four Different ways to call method asynchronously are: EndInvoke Pattern , Wait Handle, Polling Pattern, Callback Pattern