1) 每个线程包含一个ManualResetEvent成员。
2)线成退出之前调用ManualResetEvent.Set。
3)主线程在Start其他Thread之前建立一个WaitHandle[],把其他线程的ManualResetEvent.Handle放进去。
4)主线程启动其他线程,并且调用WaitHandle.WaitAll等待所有线成退出。
2)线成退出之前调用ManualResetEvent.Set。
3)主线程在Start其他Thread之前建立一个WaitHandle[],把其他线程的ManualResetEvent.Handle放进去。
4)主线程启动其他线程,并且调用WaitHandle.WaitAll等待所有线成退出。
qqchen79的意思是让你给每个线程添加ManualResetEvent,然后继续2、3、4步骤
如何声明? 用“event” 吗
2)为这个类定义一个ManualResetEvent成员,不是event,普通成员。
...
using System.Threading;namespace ConsoleApplication1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private AutoResetEvent[] evt;
public void Start(){
evt=new AutoResetEvent[2];
evt[0]=new AutoResetEvent(false);
evt[1]=new AutoResetEvent(false);
Thread t1=new Thread(new ThreadStart(ThreadMethod1));
t1.IsBackground=true;
Thread t2=new Thread(new ThreadStart(ThreadMethod2));
t2.IsBackground=true;
t1.Start();
t2.Start();
Console.WriteLine("Main thread waiting");
if(WaitHandle.WaitAll(evt))
{
Console.WriteLine("Main thread exiting.");
}
} public void ThreadMethod1(){
Thread.Sleep(3000);
Console.WriteLine("Thread 1 finished...");
evt[0].Set();
}
public void ThreadMethod2()
{
Thread.Sleep(5000);
Console.WriteLine("Thread 2 finished...");
evt[1].Set();
} static void Main(string[] args)
{
Class1 o=new Class1();
o.Start();
}
}
}
//保存
HashTable ht = new HashTable();
for(int i = 0 ; i < 10 ; i ++)
{
Thread t = new Thread(new ThreadStart(Func1));
t.IsBackGround = true;
ht.Add(i , t);
t.Start();
}
//取
ICollection keys = ht.Keys;
bool bFinashed = true;
foreach(int key in keys)
{
Thread t = (Thread)ht[key];
//下面判斷t的狀態,並設置bFinashed,只要發現一個Thread的狀態不是Stop,就將nFinashed設為false;
}
//判斷bFinashed的值
agree.