李超

cc编程笔记本。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
我觉得这个没必要称之为一种方法,和第二种方法无异,不过我感觉第二种方法是把这种方法封装起来了,而这种方法要我们自己写一个循环来不断查询异步调用的方法是否已经完成,使用该方法的人一般属于“吃饱撑的”类型的人(呵呵,我这种写这种方法的人亦如是)
 
其实就是把使用ar.WaitHandle.WaitOne()方法替换成一个While循环,假如没完成就睡眠10毫秒,用ar.IsCompleted属性来判断是否执行完毕
While (ar.IsCompleted == false) //假如没有执行完
{
   Thread.Sleep(10);//睡眠10毫秒
}
就是把ar.WaitHandle.WaitOne()替换成上面的While循环来同步线程
 
代码如下:
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, null, null);
            Thread.Sleep(10);
            Console.WriteLine("Main Thread {0} Does Some Work",
                AppDomain.GetCurrentThreadId());
            while (ar.IsCompleted == false)
            {
                Thread.Sleep(10);
            }
            Console.WriteLine("其实很简单");
            string ret = andl.EndInvoke(out threadID, ar);
            Console.WriteLine("The call executed on thread {0},with return value : {1}",
                threadID, ret);
            Console.ReadLine();
        }
    }
}
posted on 2006-08-27 11:48  coderlee  阅读(3163)  评论(0编辑  收藏  举报