此處介紹一下 AutoResetEvent的方法
下面貼一下微軟自帶的一個方法讯泣。
using System;
using System.Threading;
class ZLP_TEST
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("Main starting.");
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
// Wait for work method to signal.
autoEvent.WaitOne();
Console.WriteLine("Work method signaled.\nMain ending.");
Console.ReadKey();
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(10000);
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}
這樣點擊后就是
Paste_Image.png
sleep十秒后
Paste_Image.png
我們會注意到里面有個方法
ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod), autoEvent);
此處這個方法可以替換帶參數(shù)啟動一個new Thread昨稼。 上面這個方法已經(jīng)非常簡練假栓,建議這么使用,下面這個方法挺繁瑣的匾荆。
下面的方法其實也是帶參數(shù)新建線程的一個方法杆烁。
我們先新建一個類
public class Test
{
AutoResetEvent autoEvent;
public Test(AutoResetEvent autoevent)
{
autoEvent = autoevent;
}
public void WorkMethod()
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(10000);
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)autoEvent).Set();
}
}
那么將原先工程中的替換一下
using System;
using System.Threading;
class ZLP_TEST
{
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main()
{
Console.WriteLine("Main starting.");
//原先的做法
//ThreadPool.QueueUserWorkItem(
// new WaitCallback(WorkMethod), autoEvent);
//目前的做法
Test a = new Test(autoEvent);
Thread b = new Thread(new ThreadStart(a.WorkMethod));
b.Start();
// Wait for work method to signal.
autoEvent.WaitOne();
Console.WriteLine("Work method signaled.\nMain ending.");
Console.ReadKey();
}
static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
// Simulate time spent working.
Thread.Sleep(10000);
// Signal that work is finished.
Console.WriteLine("Work ending.");
((AutoResetEvent)stateInfo).Set();
}
}