李超

cc编程笔记本。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
第二种方法是借助返回的IAsyncHandle的WaitHandle属性的WaitOne()方法实现线程同步后,执行代码,然后将要执行的代码执行后随时可调用EndInvoke方法。
 
示例代码基本没有什么改动,只是在BeginInvoke方法后执行一个ar.WaitHandle.WaitOne()方法,该方法将阻塞主线程使主线程等待返回ar的begininvoke调用的方法的线程执行完毕(不要怪我说话有点绕,我是说的详细,否则你弄不明白,仔细看这句话就明白了^o^)。
 
本着一切代码都是纸老虎的原则,请仔细分析下面的代码  其实和示例1基本无异 ,只是使用WaitOne()方法同步了一下线程而已
 
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());
            ar.AsyncWaitHandle.WaitOne();//执行该方法时主线程将等待辅助线程执行完毕,使两线程同步后再执行以下语句
            Console.WriteLine("其实很简单");//执行一些方法
            string ret = andl.EndInvoke(out threadID, ar);//使用EndInvoke来获取返回结果和传入ref和out的变量获取修改后的实例的位置(这我就不太好用语言来表述了,你自己心领神会吧)
            Console.WriteLine("The call executed on thread {0},with return value : {1}",
                threadID, ret);
            Console.ReadLine();
        }
    }
}
posted on 2006-08-27 11:47  coderlee  阅读(8981)  评论(1编辑  收藏  举报