Begin Invoke With All Parameters C# with Example



Begin Invoke With All Parameters C# with Example

 using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace CSharpMultiThreading
{
    public delegate int Addition(int x, int y);

    class InvokingMethodAsyncronously
    {
		private static bool isDone = false;
					
		static void Main(string[] args)
		{			
			// Print out the ID of the executing thread.
			Console.WriteLine("Main() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId);

			// Invoke Add() on a secondary thread.
			Addition b = new Addition(Add);
			IAsyncResult iftAR = b.BeginInvoke(10, 10, new AsyncCallback(AddComplete), "Main() Method is being Over Now.");
			
            while (!isDone)
            {
                Console.WriteLine("Working...");
                Thread.Sleep(1000);
            }
		}

		static void AddComplete(IAsyncResult itfAR)
		{
			Console.WriteLine("AddComplete() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId);
			Console.WriteLine("Your addition is complete");

			// Now get the result.
			AsyncResult ar = (AsyncResult)itfAR;
			Addition b = (Addition)ar.AsyncDelegate;
			string msg = (string)itfAR.AsyncState;
			Console.WriteLine("10 + 10 is {0}.\n{1}", b.EndInvoke(itfAR), msg);
			isDone = true;
		}
		
		static int Add(int x, int y)
		{
		// Print out the ID of the executing thread.
		Console.WriteLine("Add() invoked on thread {0}.",Thread.CurrentThread.ManagedThreadId);

		// Pause to simulate a lengthy operation.
		Thread.Sleep(5000);
		return x + y;
		}
    }
}
 

0 Comment's

Comment Form

Submit Comment