Sunday, January 20, 2013

Difference between BeginInvoke and Invoke in Delegates?


Delegate.Invoke

Delegate.Invoke works on the same thread. It is used to execute a delegate on the same thread. No other thread is used to execute a delegate.

Delegate.BeginInvoke

Delegate.BeginInvoke works on a separate thread, not on the same thread. It is used to execute a delegate asynchronously. BeginInvoke doesn’t block your current thread, it execute separately so it execute in the background.

Note: If you use BeginInvoke, you have to use EndInvoke to get the result.

Example

    public class MulticastDelegate
    {
        delegate string MyDelegate(string message);

        static void Main()
        {
            MyDelegate objMyDelegate1 = new MyDelegate(WriteLog);
            MyDelegate objMyDelegate2 = new MyDelegate(SendEmail);

            AsyncCallback objcallback = new AsyncCallback(DisplayResult);
            Console.WriteLine("Start..");

            objMyDelegate1.BeginInvoke("Operation failed..", objcallback, null);
            objMyDelegate2.BeginInvoke("Operation failed..", objcallback, null);

            Console.WriteLine("Main thread continuing..");

            Thread.Sleep(3000);
            Console.WriteLine("Done..");

            Console.ReadLine();
        }

        static void DisplayResult(IAsyncResult result)
        {
            string format = (string)result.AsyncState;
            AsyncResult delegateResult = (AsyncResult)result;
            MyDelegate delegateInstance = (MyDelegate)delegateResult.AsyncDelegate;

            Console.WriteLine(delegateInstance.EndInvoke(result));
        }

        static string WriteLog(string message)
        {
            Thread.Sleep(2000);
            Console.WriteLine("WriteLog :- " + message);

            return "WriteLog Done!";
        }

        static string SendEmail(string message)
        {
            Thread.Sleep(1000);
            Console.WriteLine("SendEmail :- " + message);

            return "SendEmail Done!";
        }
     }
}

Output

Start..
Main thread continuing..
SendEmail :- Operation failed..
SendEmail Done!
WriteLog :- Operation failed..
WriteLog Done!
Done..

No comments:

Post a Comment