多线程编程中Join与WaitOne的区别
举例说明:
Join:在一个线程MainThread中开启一个新的线程NewThread,在完成初始化并启动NewThread的操作后,调用Join,则MainThread堵塞,直到NewThread执行完毕,MainThread才继续执行。
using System;
using System.Threading;
class IsThreadPool
{
static void Main()
{
Console.WriteLine("MainThread start.");
AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread NewThread =
new Thread(new ThreadStart(ThreadMethod));
NewThread.Start();
// Wait for foreground thread to end.
NewThread.Join();
Console.WriteLine("MainThread end.");
}
static void ThreadMethod()
{
Console.WriteLine("haha,NewMethod");
}
}
using System.Threading;
class IsThreadPool
{
static void Main()
{
Console.WriteLine("MainThread start.");
AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread NewThread =
new Thread(new ThreadStart(ThreadMethod));
NewThread.Start();
// Wait for foreground thread to end.
NewThread.Join();
Console.WriteLine("MainThread end.");
}
static void ThreadMethod()
{
Console.WriteLine("haha,NewMethod");
}
}
运行结果:
MainThread start.
haha,NewMethod
MainThread end.
WaitOne:在一个线程MainThread中开启一个新的线程NewThread,在完成初始化并启动NewThread的操作后,调用WaitOne,则MainThread堵塞,直到在NewThread中调用Set,MainThread才继续执行。
using System;
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("MainThread start.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
autoEvent.WaitOne();
Console.WriteLine("MainThread continue.");
Console.WriteLine("MainThread end.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work start.");
// Simulate time spent working.
Thread.Sleep(new Random().Next(100, 2000));
// Signal that work is finished.
Console.WriteLine("Work end.");
((AutoResetEvent)stateInfo).Set();
}
}
using System.Threading;
class WaitOne
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("MainThread start.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
autoEvent.WaitOne();
Console.WriteLine("MainThread continue.");
Console.WriteLine("MainThread end.");
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work start.");
// Simulate time spent working.
Thread.Sleep(new Random().Next(100, 2000));
// Signal that work is finished.
Console.WriteLine("Work end.");
((AutoResetEvent)stateInfo).Set();
}
}
运行结果:
MainThread start.
Work start.
Work end.
MainThread end.
posted on 2006-07-10 18:16 bartholomew 阅读(1749) 评论(0) 编辑 收藏 举报