C# Thread、lock
2021-06-27 19:05
标签:color ati 代码 writer start static 按键 object message C# Thread、lock 标签:color ati 代码 writer start static 按键 object message 原文地址:https://www.cnblogs.com/gygtech/p/10070674.html class Program
{
private static readonly object obj = new object();
static void Main(string[] args)
{
Thread th1 = new Thread(TestLock);
Thread th2 = new Thread(TestLock1);
th1.IsBackground = true;
th2.IsBackground = true;
th2.Start();
th1.Start();
#region 按任意键继续
Console.Write("按任意键继续!");
//此代码会提示用户按任意键,然后在用户按键前暂停程序。
Console.ReadKey(true);
#endregion 按任意键继续
}
private static void TestLock()
{
lock (obj)
{
for (int i = 0; i 10000; i++)
{
var message = i.ToString();
string logFileName = @"F:\Log\" + DateTime.Now.ToString("yyyyMMdd") + "Log" + ".txt";
StreamWriter sr = new StreamWriter(logFileName, true);
try
{
sr.WriteLine(message);
}
catch
{
Console.WriteLine(message);
}
finally
{
sr.Close();
}
}
}
}
private static void TestLock1()
{
lock (obj)
{
for (int i = 10000; i 20000; i++)
{
var message = "Count:" + i.ToString();
string logFileName = @"F:\Log\" + DateTime.Now.ToString("yyyyMMdd") + "Log" + ".txt";
StreamWriter sr = new StreamWriter(logFileName, true);
try
{
sr.WriteLine(message);
}
catch
{
Console.WriteLine(message);
}
finally
{
sr.Close();
}
}
}
}
}