您的位置:首页 > 大数据 > 人工智能

AutoResetEvent WaitOne和Set使用实例

2011-07-28 15:25 501 查看
/// <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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  path thread string 测试