Main.

ThreadProc method waits again.

That guarantee would require a second AutoResetEvent lock.

Main would write many values between any two read operations.

    class Program
    {
        //Initially not signaled.
        private const int NumIterations = 100;

        private static readonly AutoResetEvent MyResetEvent = new AutoResetEvent(false);

        private static int _number;

        public static void Main()
        {
            //Create and start the reader thread.
            var myReaderThread = new Thread(new ThreadStart(MyReadThreadProc));
            myReaderThread.Name = "ReaderThread";
            myReaderThread.Start();

            for (int i = 1; i <= NumIterations; i++)
            {
                Console.WriteLine("Writer thread writing value: {0}", i);
                _number = i;

                //Signal that a value has been written.
                MyResetEvent.Set();

                //Give the Reader thread an opportunity to act.
                Thread.Sleep(1);
            }

            //Terminate the reader thread.
            myReaderThread.Abort();

            Console.ReadKey();
        }

        private static void MyReadThreadProc()
        {
            while (true)
            {
                //The value will not be read until the writer has written
                // at least once since the last read.
                MyResetEvent.WaitOne();
                Console.WriteLine("{0} reading value: {1}", Thread.CurrentThread.Name, _number);
            }
        }
    }

 

相关文章:

  • 2022-02-21
  • 2021-12-04
  • 2021-09-23
  • 2021-05-22
  • 2022-03-10
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-05-04
  • 2022-02-15
  • 2021-07-23
  • 2021-11-10
  • 2022-01-26
相关资源
相似解决方案