0

以下是我的代码,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; }
    }

发生了什么事,为什么它总是在等待,知道吗?

4

1 回答 1

1

您的CloseAll方法中有一个无限循环。当所有事件都发出信号时,WaitAll返回。true您不需要空的 while 循环,只需添加以下行:

WaitHandle.WaitAll(meList.ToArray());
于 2012-11-14T22:29:52.480 回答