(三)线程--等待句柄

(一).描述
本示例代码实现线程等待等待执行,比如一个线程在执行之前要等待所有其它线程或某个线程
先执行完成,或者等待其它线程至少一个执行完成.
(二).代码
using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace 等待句柄
{
//委托声明(函数签名)
delegate string MyMethodDelegate();
class MyClass
{
//要调用方法1
public string Write1()
{
for(double i = 0; i < 100000000000;i++) //此数值大小可以根据自己的环境修改,
//目的是让此方法延长时间而已
{
//延长时间(模拟实际任务)
}
Console.WriteLine("执行方法1");
return "";
}

//要调用方法2
public string Write2()
{
Console.WriteLine("执行方法2");
return "22222222222222";
}

//要调用方法3
public string Write3()
{
Console.WriteLine("执行方法3");
return "33333333333333";
}

[STAThread]
static void Main(string[] args)
{
MyClass myClass = new MyClass();
MyMethodDelegate d1 = new MyMethodDelegate(myClass.Write1);
MyMethodDelegate d2 = new MyMethodDelegate(myClass.Write2);
MyMethodDelegate d3 = new MyMethodDelegate(myClass.Write3);

AsyncResult myResult1,myResult2,myResult3; //此类封闭异步委托异步调用的结果,通过AsyncResult得到结果.
myResult1 = (AsyncResult)d1.BeginInvoke(null,null); //调用

myResult2 = (AsyncResult)d2.BeginInvoke(null,null);

myResult3 = (AsyncResult)d3.BeginInvoke(null,null);

//建立WaitHandle数组对象
WaitHandle[] waitHandle = new WaitHandle[3]{myResult1.AsyncWaitHandle,myResult2.AsyncWaitHandle,myResult3.AsyncWaitHandle};

/*
try
{
//等待三个异步方法中的至少一个执行完成,才继续执行下面的语句
WaitHandle.WaitAny(waitHandle);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
*/

myResult1.AsyncWaitHandle.WaitOne(); //如果当前异步方法还没有完成,此异步方法执行完毕才往下执行
myResult2.AsyncWaitHandle.WaitOne();
myResult3.AsyncWaitHandle.WaitOne();

/*
myResult1.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1),false); //如果当前异步方法还没有完成,则等待一秒的时间执行此方法; 如果一秒后此方法还未完成的话,则不再等待,继续往下执行
myResult2.AsyncWaitHandle.WaitOne();
myResult3.AsyncWaitHandle.WaitOne();
*/

Console.WriteLine("测试等待句柄"); //标记语句用.
Console.Read();
}
}
}

本示例代码已经测试,能够正常运行!

(三).示例下载
http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar

Published At
Categories with Web编程
Tagged with
comments powered by Disqus