问候 Rainer This is what I expected, just wanted to make sure. Would this be thread safe?: List<MyTyp> aList = new List<MyType>(); // one thread removes elements from the list like Monitor.Enter(aList) try { MyTyp x = aList[0]; aList.Remove(x); } finally{ Monitor.Exit(aList) } // While in the same momen a other thread adds a element like MyType y = new MyType(); Monitor.Enter(aList) try { aList.Add(y); } finally{ Monitor.Exit(aList); } Regards Rainer 首先是锁定比Monitor更整洁(它在幕后使用Monitor) 锁定(aList) { //做东西 } 其次你的解决方案是可以的,但它避免了与问题有关的主要问题b $ b问题当我尝试 取出一些东西时,如果清单是空的怎么办? 1)你不能测试空的锁定外面在wgich你得到的地区 元素 2)你必须要么返回一些表明它是空的东西或者等待 直到它不是'' t空,这将需要等待和脉冲方法在 监视器上 3)如果你有一个固定长度的列表队列,那么同样的问题适用于 添加方法firstly"lock" is neater than Monitor (it uses Monitor behind the scenes)lock(aList){// do stuff}secondly you''re solution is OK as far as it goes but it avoids the mainissue which is to do with the question "what if the list is empty when I tryto take something off it?"1) You cannot test for empty outside of the locked region in wgich you getthe element2) You must either return something indicating that it was empty or waituntil it isn''t empty which will require the Wait and Pulse methods on theMonitor3) If you have a fixed length list queue then the same issues apply to theadd method 这篇关于列表与LT; T&GT;线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 08:35
查看更多