AutoResetEvent WaitOne和Set使用实例

        /// <summary>
        /// 一共写100行
        /// </summary>
        private const int maxLineNumber = 100;

        /// <summary>
        /// 测试文件路径
        /// </summary>
        private const string Path = @"D:\1.txt";

        static void Main(string[] args)
        {
            AutoResetEvent autoReset = new AutoResetEvent(false);

            if (!File.Exists(Path))
            {
                FileStream fs = File.Create(Path);
                fs.Close();
            }
            ////开启新线程用来读
            Thread readThread =
            new Thread(new ThreadStart(() =>
            {
                for (int i = 0; i < maxLineNumber; i++)
                {
/////等待写线程Set
                    autoReset.WaitOne();
                    StreamReader sr = File.OpenText(Path);
                    Console.WriteLine(sr.ReadToEnd());
                    sr.Close();
                }
            }));
            readThread.Start();

            ////写线程每写一行,释放一个读线程去读取刚写入的文字
            for (int i = 0; i < maxLineNumber; i++)
            {
                File.WriteAllText(Path, i.ToString() + "\r\n");
                autoReset.Set();
                Thread.Sleep(1000);
            }


            Console.ReadKey();
        }


你可能感兴趣的:(thread,String,测试,Path)