Wednesday, November 4, 2015

Asynchronous Method Calls using Delegate

Asynchronous method call means main execution goes continue and method executed parallel, when method execution gets completed it notifies back to main execution program / caller (client).

Example
namespace AsyncCallBack
{
    class Program
    {
        public delegate string delTask();
        public static string results;
        static void Main(string[] args)
        {
            clsBigTask objclsTask = new clsBigTask();
            delTask del = objclsTask.BigTask;
          
            AsyncCallback asyncCall = new AsyncCallback(CallBackMethod);
            del.BeginInvoke(asyncCall, del);
          
            Console.WriteLine("Main task completed @" + DateTime.Now.ToString());
            Console.ReadLine();
        }

        public static void CallBackMethod(IAsyncResult result)
        {
            delTask mydel = (delTask)result.AsyncState;
            results = mydel.EndInvoke(result);
            Console.WriteLine(results);
        }
    }

    public class clsBigTask
    {
        public string BigTask()
        {
            Thread.Sleep(6000);
            return "Big Task completed";
        }
    }
}

Output

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...