【发布时间】:2010-04-02 00:13:56
【问题描述】:
使用这个小型测试应用程序来学习线程/锁定。我有以下代码,我认为该行应该只写入控制台一次。但是,它似乎没有按预期工作。关于为什么的任何想法?我要做的是将此 Lot 对象添加到列表中,然后如果任何其他线程尝试点击该列表,它将阻塞。我在这里完全滥用了锁吗?
class Program
{
static void Main(string[] args)
{
int threadCount = 10;
//spin up x number of test threads
Thread[] threads = new Thread[threadCount];
Work w = new Work();
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(new ThreadStart(w.DoWork));
}
for (int i = 0; i < threadCount; i++)
{
threads[i].Start();
}
// don't let the console close
Console.ReadLine();
}
}
public class Work
{
List<Lot> lots = new List<Lot>();
private static readonly object thisLock = new object();
public void DoWork()
{
Lot lot = new Lot() { LotID = 1, LotNumber = "100" };
LockLot(lot);
}
private void LockLot(Lot lot)
{
// i would think that "Lot has been added" should only print once?
lock (thisLock)
{
if(!lots.Contains(lot))
{
lots.Add(lot);
Console.WriteLine("Lot has been added");
}
}
}
}
【问题讨论】:
-
为什么你认为它应该只打印一次?
标签: c# .net multithreading locking