Calling Asynchronously Method Using BeginInvoke Method in C#

Introduction

Sometimes we need to call a method asynchronously and don't want to wait until it completes execution.

How to Make Asynchronous Calls?

  1. Asynchronous calls are made by using delegates. A delegate is an object that wraps a function. Delegates provide a synchronous function and also provides methods for calling the wrapped function asynchronously.
  2. Those methods are BeginInvoke() and EndInvoke(). The parameter lists of these methods depend on the signature of the delegate function.
  3. BeginInvoke() is used to initiate the asynchronous call of the method. It has the same parameters as the function name, and two additional parameters. BeginInvoke() returns immediately and does not wait for the asynchronous call to complete. BeginInvoke() returns an IAsyncResult object.
  4. The EndInvoke() function is used to retrieve the results of the asynchronous call method. It can be called anytime after the BeginInvoke() method. If the asynchronous call has not completed yet, EndInvoke() blocks until it completes. The parameters of the EndInvoke() function includes the out and ref parameters that the wrapped function has, plus the IAsyncResult object that is returned by the BeginInvoke() method.
  5. The following is an example of a delegate and its BeginInvoke() and EndInvoke() methods.    
public class Demo
{
    // Declare Delegate
    delegate string MethodDelegate(int CallTime, out int ExecThread);

    // will have the following BeginInvoke() and EndInvoke methods:
    IAsyncResult MethodDelegate.BeginInvoke(int iCallTime, out int iExecThread, AsyncCallback cb, object AsyncState);

    string MethodDelegate.EndInvoke(out int iExecThread, IAsyncResult ar);
}

Code for Asynchronously Method:

public class Demo
{
    #region MEMEBER VARIABLES

    private delegate Boolean DelLogException(String PrmStrLogTo, String PrmExceptionLog);

    #endregion MEMBER VARIABLES

    public Boolean AsyncLogException(String PrmStrLogTo, String PrmExceptionLog)
    {
        Boolean blnExceptionLogged = false;
        try
        {
            DelLogException objDelLogException = new DelLogException(BeginLogException);
            IAsyncResult result = objDelLogException.BeginInvoke(PrmStrLogTo, PrmExceptionLog, null, null);
            blnExceptionLogged = objDelLogException.EndInvoke(result);
        }
        catch
        {
            throw;
        }
        return blnExceptionLogged;
    }

    private Boolean BeginLogException(String PrmStrLogTo, String PrmExceptionLog)
    {
        Boolean blnExecutedWithoutError = true;
        try
        {
            // Code here
        }
        catch (Exception) { blnExecutedWithoutError = false; }
        return blnExecutedWithoutError;
    }
}


Recommended Free Ebook
Similar Articles