李超

cc编程笔记本。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
这个和以上三种方法不同,也比较抽象难以理解,但是我想一个正常人的智商多看几遍理解起来是没有问题的。
 
我先说下回调函数,就是我在第一篇的时候讲过的,委托类型的BeginInvoke方法除被调用函数的参数列表外还另外加了两个参数,第一个参数就是回调方法的委托(该回调方法必须是无返回的,因为这个参数必须是System.AsyncCallBack委托,这个委托指向的是一个无返回的方法,而且这个方法只能由一个参数,参数类型是IAsyncResult,但是可以使用该参数传递任何object),第二个参数是一个param参数列表,是执行该回调方法的时候要用到的参数(应该能理解),也可以是执行BeginInvoke方法时返回的那个IAsyncResult,这样就可以在回调方法中通过,IAsyncResult.AsyncState属性来返回BeginInvoke方法所属的委托,通过这样来在回调函数中执行EndInvoke方法。
 
以下是示例代码
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace sample
{
    class AsyncDemo
    {
        public string TestMethod(int callDuration, out int threadid)
        {
            Console.WriteLine("Test Method begins");
            Thread.Sleep(callDuration);
            threadid = AppDomain.GetCurrentThreadId();
            return "MyCallTime was" + callDuration.ToString();
        }
    }
    public delegate string AsyncDelegate(int callDuration, out int threadid);
    class Program
    {
        static void Main(string[] args)
        {
            int threadID;
            AsyncDemo ad = new AsyncDemo();
            AsyncDelegate andl = new AsyncDelegate(ad.TestMethod);
            IAsyncResult ar = andl.BeginInvoke(3000, out threadID,
                new AsyncCallback(CallBackMethod), andl);
            Thread.Sleep(10);
            Console.WriteLine("Main Thread {0} Does Some Work",
                AppDomain.GetCurrentThreadId());

            Console.ReadLine();
        }
 
        static void CallBackMethod(IAsyncResult ar) //无返回而且只有一个IAsyncResult类型的参数ar
        {
            int j;
            AsyncDelegate andl = (AsyncDelegate)ar.AsyncState;
            Console.WriteLine(andl.EndInvoke(out j, ar));
        }
    }
}
posted on 2006-08-27 11:48  coderlee  阅读(6888)  评论(0编辑  收藏  举报