What is Delegate?
What is Asynchronous Delegate?
BeginInvoke() method
EndInvoke() method
IAsyncResult Interface
AsyncCallback Delegate
Ways to call methods asynchronously using BeginInvoke() and EndInvoke()
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