程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> 利用委托實現異步調用

利用委托實現異步調用

編輯:C#基礎知識
  1. 同步調用示例(委托是一個類型安全的,面向對象的指針)
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                int answer = op (10, 20);
                //after Add() executed, the folow goes on.
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }
    剖析代碼的繼承關系: 代理Operate經歷了3次派生(綠色部分),實現了一個構造和3個虛擬函數(黃色部分).

    image
  2. 異步調用方法:線程異步了,但是主線程等待次線程返回才能獲得結果,阻塞在EndInvoke上.
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke(10,20,null,null);
                Console.WriteLine ("Doing more in Main() exected immediately.");
                //the thread susppend on EndInvoke while 'result' is ready!
                int answer = op.EndInvoke (result);
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }

  3. 同步調用:如果線程沒有返回,不要一直問何時返回,每間隔500ms做該做的事情!!!
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}\n",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke(10,20,null,null);
                //while result is not OK, do it every 500 ms.
                while (!result.AsyncWaitHandle.WaitOne(500,true)) {//result.IsCompleted
                    Console.WriteLine ("Doing more work in Main().");
                }
                int answer = op.EndInvoke (result);
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }

  4. 線程回調: 好吧,干脆你返回的時候通知我,我該干啥不耽擱!
    using System;
    using System.Threading;
    
    /// <summary>
    /* Main() invoked on thread:1
    Main() execute no need to wait any more.
    Add() invoked on thread:3
    AddComplete() invoked on thread:3
    Your Addition is complete.
    */
    /// </summary>
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void AddComplete(IAsyncResult ia)
            {
                Console.WriteLine ("AddComplete() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Get Result value
                System.Runtime.Remoting.Messaging.AsyncResult ar=
                    (System.Runtime.Remoting.Messaging.AsyncResult)ia;
                Operate op = (Operate)ar.AsyncDelegate;
                Console.WriteLine ("The value is {0}.", op.EndInvoke (ia));
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke (10, 20, new AsyncCallback (AddComplete), null);
                Console.WriteLine ("Main() execute no need to wait any more.");
                Console.ReadKey ();
            }
        }
    }

  5. 主線程向次線程傳遞對象,通知!
    using System;
    using System.Threading;
    
    /// <summary>
    /*

    Main() invoked on thread:1
    Main() execute no need to wait any more.
    Add() invoked on thread:3
    AddComplete() invoked on thread:3
    The value is 30.
    The Main() thread is :1

    */
    /// </summary>
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void AddComplete(IAsyncResult ia)
            {
                Console.WriteLine ("AddComplete() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Get Result value
                System.Runtime.Remoting.Messaging.AsyncResult ar=
                    (System.Runtime.Remoting.Messaging.AsyncResult)ia;
                Operate op = (Operate)ar.AsyncDelegate;
                Console.WriteLine ("The value is {0}.", op.EndInvoke (ia));
                Thread thread = (Thread)ia.AsyncState;
                Console.WriteLine ("The Main() thread is :{0}", thread.GetHashCode());
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke (10, 20, 
                    new AsyncCallback (AddComplete),Thread.CurrentThread);
                Console.WriteLine ("Main() execute no need to wait any more.");
                Console.ReadKey ();
            }
        }
    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved