111,126
社区成员
发帖
与我相关
我的任务
分享
class Program
{
static void Main(string[] args)
{
try
{
Thread t1 = new Thread(Logger.Write);
t1.Name = "t1";
Thread t2 = new Thread(Logger.Write);
t2.Name = "t2";
t1.Start();
t2.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class Logger
{
const int C = 10;
public static void Write()
{
using (FileStream fs = new FileStream("c:\\a.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
int i = 0;
while (i < C)
{
// 下行代码如果注释,可以运行,但不知道是否存在潜在的问题。
//Thread.Sleep(100);
sw.WriteLine(Thread.CurrentThread.Name + " -- " + DateTime.Now.ToLocalTime());
i++;
}
}
}
}
}
public static void Write()
{
static object l_obj = new object();
lock (l_obj) {
using (FileStream fs = new FileStream("c:\\a.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
int i = 0;
while (i < C)
{
// 下行代码如果注释,可以运行,但不知道是否存在潜在的问题。
//Thread.Sleep(100);
sw.WriteLine(Thread.CurrentThread.Name + " -- " + DateTime.Now.ToLocalTime());
i++;
}
}
}
}
}