C# BeginInvoke和EndInvoke异步调用

首先做一个Delegate的测试类

using System;
using System.Threading; 

namespace Examples.AdvancedProgramming.AsynchronousOperations
{
    public class AsyncDemo 
    {
        // The method to be executed asynchronously. 
        public string TestMethod(int callDuration, out int threadId) 
        {
            Console.WriteLine("Test method begins.");
            Thread.Sleep(callDuration);
            threadId = Thread.CurrentThread.ManagedThreadId;
            return String.Format("My call time was {0}.", callDuration.ToString());
        }
    }
    // The delegate must have the same signature as the method 
    // it will call asynchronously. 
    public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}

 

  • EndInvoke的使用,它会一直阻塞主进程,等待异步调用的进程结束直到有返回值返回
    using System;
    using System.Threading;
    
    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncMain 
        {
            public static void Main() 
            {
                // The asynchronous method puts the thread id here. 
                int threadId;
    
                // Create an instance of the test class.
                AsyncDemo ad = new AsyncDemo();
    
                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
    
                // Initiate the asychronous call.
                IAsyncResult result = caller.BeginInvoke(3000, 
                    out threadId, null, null);
    
                Thread.Sleep(0);
                Console.WriteLine("Main thread {0} does some work.",
                    Thread.CurrentThread.ManagedThreadId);
    
                // Call EndInvoke to wait for the asynchronous call to complete, 
                // and to retrieve the results. 
                string returnValue = caller.EndInvoke(out threadId, result);
    
                Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
            }
        }
    }
    
    /* This example produces output similar to the following:
    
    Main thread 1 does some work.
    Test method begins.
    The call executed on thread 3, with return value "My call time was 3000.".
     */
    

     

  • WaitHandler的使用,此方法的调用方无限期阻止,直到当前实例收到信号。
    using System;
    using System.Threading;
    
    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncMain 
        {
            static void Main() 
            {
                // The asynchronous method puts the thread id here. 
                int threadId;
    
                // Create an instance of the test class.
                AsyncDemo ad = new AsyncDemo();
    
                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
    
                // Initiate the asychronous call.
                IAsyncResult result = caller.BeginInvoke(3000, 
                    out threadId, null, null);
    
                Thread.Sleep(0);
                Console.WriteLine("Main thread {0} does some work.",
                    Thread.CurrentThread.ManagedThreadId);
    
                // Wait for the WaitHandle to become signaled.
                result.AsyncWaitHandle.WaitOne();
    
                // Perform additional processing here. 
                // Call EndInvoke to retrieve the results. 
                string returnValue = caller.EndInvoke(out threadId, result);
    
                // Close the wait handle.
                result.AsyncWaitHandle.Close();
    
                Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
            }
        }
    }
    
    /* This example produces output similar to the following:
    
    Main thread 1 does some work.
    Test method begins.
    The call executed on thread 3, with return value "My call time was 3000.".
     */
    

     

  • 通过IAsyncResult类的IsComplete判断是否异步调用完成
    using System;
    using System.Threading;
    
    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncMain 
        {
            static void Main() {
                // The asynchronous method puts the thread id here. 
                int threadId;
    
                // Create an instance of the test class.
                AsyncDemo ad = new AsyncDemo();
    
                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
    
                // Initiate the asychronous call.
                IAsyncResult result = caller.BeginInvoke(3000, 
                    out threadId, null, null);
    
                // Poll while simulating work. 
                while(result.IsCompleted == false) {
                    Thread.Sleep(250);
                    Console.Write(".");
                }
    
                // Call EndInvoke to retrieve the results. 
                string returnValue = caller.EndInvoke(out threadId, result);
    
                Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", threadId, returnValue);
            }
        }
    }
    
    /* This example produces output similar to the following:
    
    Test method begins.
    .............
    The call executed on thread 3, with return value "My call time was 3000.".
     */
    

     

  • 设置回调函数,在异步完成后,调用回调函数
    using System;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;
    
    namespace Examples.AdvancedProgramming.AsynchronousOperations
    {
        public class AsyncMain 
        {
            static void Main() 
            {
                // Create an instance of the test class.
                AsyncDemo ad = new AsyncDemo();
    
                // Create the delegate.
                AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
    
                // The threadId parameter of TestMethod is an out parameter, so 
                // its input value is never used by TestMethod. Therefore, a dummy 
                // variable can be passed to the BeginInvoke call. If the threadId 
                // parameter were a ref parameter, it would have to be a class- 
                // level field so that it could be passed to both BeginInvoke and  
                // EndInvoke. 
                int dummy = 0;
    
                // Initiate the asynchronous call, passing three seconds (3000 ms) 
                // for the callDuration parameter of TestMethod; a dummy variable  
                // for the out parameter (threadId); the callback delegate; and 
                // state information that can be retrieved by the callback method. 
                // In this case, the state information is a string that can be used 
                // to format a console message.
                IAsyncResult result = caller.BeginInvoke(3000,
                    out dummy, 
                    new AsyncCallback(CallbackMethod),
                    "The call executed on thread {0}, with return value \"{1}\".");
    
                Console.WriteLine("The main thread {0} continues to execute...", Thread.CurrentThread.ManagedThreadId);
    
                // The callback is made on a ThreadPool thread. ThreadPool threads 
                // are background threads, which do not keep the application running 
                // if the main thread ends. Comment out the next line to demonstrate 
                // this.
                Thread.Sleep(4000);
    
                Console.WriteLine("The main thread ends.");
            }
    
            // The callback method must have the same signature as the 
            // AsyncCallback delegate. 
            static void CallbackMethod(IAsyncResult ar) 
            {
                // Retrieve the delegate.
                AsyncResult result = (AsyncResult) ar;
                AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate;
    
                // Retrieve the format string that was passed as state  
                // information. 
                string formatString = (string) ar.AsyncState;
    
                // Define a variable to receive the value of the out parameter. 
                // If the parameter were ref rather than out then it would have to 
                // be a class-level field so it could also be passed to BeginInvoke. 
                int threadId = 0;
    
                // Call EndInvoke to retrieve the results. 
                string returnValue = caller.EndInvoke(out threadId, ar);
    
                // Use the format string to format the output message.
                Console.WriteLine(formatString, threadId, returnValue);
            }
        }
    }
    
    /* This example produces output similar to the following:
    
    The main thread 1 continues to execute...
    Test method begins.
    The call executed on thread 3, with return value "My call time was 3000.".
    The main thread ends.
     */
    

     

    具体请参照

    http://msdn.microsoft.com/en-us/library/2e08f6yc(v=vs.110).aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值