C#WaitHandle.WaitAll()总是在等待

时间:2012-11-14 22:27:26

标签: c#

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

发生了什么,为什么它总是在等待,任何想法?

1 个答案:

答案 0 :(得分:1)

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

WaitHandle.WaitAll(meList.ToArray());