// Need this for the Thread.Sleep() call.
using System.Threading;
using System;

 

namespace SyncDelegate
{
    public delegate int BinaryOp(int x, int y);

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Synch Delegate Review *****");
                        
            Console.WriteLine("Main() invoked on thread {0}.",
              Thread.CurrentThread.ManagedThreadId);

            BinaryOp b = new BinaryOp(Add);

         
          IAsyncResult iftAR= b.BeginInvoke(10, 10,null,null);
           while (!iftAR.IsCompleted)
           {
               Console.WriteLine("Doing more work in Main()!");
               Thread.Sleep(1000);
           }
            int answer = b.EndInvoke(iftAR);
                   
            Console.WriteLine("10 + 10 is {0}.", answer);
            Console.ReadLine();
        }

        #region Very time consuming addition!
        static int Add(int x, int y)
        {
           Console.WriteLine("Add() invoked on thread {0}.",
           Thread.CurrentThread.ManagedThreadId);

           Thread.Sleep(8000);
           return x + y;
        }
        #endregion
    }
}

 

posted on 2010-06-30 11:20  TsingCai  阅读(655)  评论(0编辑  收藏  举报