以下是我的代码,wait all 方法总是在等待。
class Program
{
static StreamWriter _fileStream;
static void Main(string[] args)
{
_fileStream = File.CreateText(@"C:\Praveen\HelloThread.txt");
List<ManualResetEvent> meList = new List<ManualResetEvent>();
ManualResetEvent currentEvent = new ManualResetEvent(true);
ManualResetEvent nextEvent = new ManualResetEvent(false);
meList.Add(currentEvent);
int length = 10;
Data data = null;
Console.WriteLine("Writing started...");
for (int i = 0; i < length; i++)
{
data = new Data { CurrentEvent = currentEvent, Number = i, NextEvent = nextEvent };
ThreadPool.QueueUserWorkItem(PrintMsg, data);
meList.Add(nextEvent);
currentEvent = nextEvent;
nextEvent = nextEvent = new ManualResetEvent(false);
}
CloseAll(meList);
Console.ReadLine();
}
private static void CloseAll(List<ManualResetEvent> meList)
{
Console.WriteLine("Requested to close all...");
while (WaitHandle.WaitAll(meList.ToArray()))
{
}
Console.WriteLine("Done with the writing...");
}
private static void PrintMsg(object state)
{
Data data = state as Data;
data.CurrentEvent.WaitOne();
string msg = "Hello times...";
for (int j = 0; j < 5; j++)
{
_fileStream.WriteLine(msg + data.Number);
Console.WriteLine(msg + data.Number);
}
data.NextEvent.Set();
}
}
public class Data
{
public ManualResetEvent CurrentEvent { get; set; }
public ManualResetEvent NextEvent { get; set; }
public int Number { get; set; }
}
发生了什么事,为什么它总是在等待,知道吗?