【发布时间】:2010-03-24 05:35:17
【问题描述】:
我想问几个关于在 .Net 中使用 Monitor 类的问题。
要了解问题,请查看以下代码。
public class MyClass
{
private List<int> _MyCollection = new List<int>();
public void GetLock()
{
Monitor.Enter(_MyCollection);
}
public void ReleaseLock()
{
Monitor.Exit(_MyCollection);
}
public void UpdateCollection(/*anyparam*/)
{
//update collection without lock on collection
}
}
public class MyAppMain
{
private static MyClass myclass = new MyClass();
public static void main(args)
{
try
{
myclass.GetLock();
//an operation that does not do any update on myclass but wanted
//to ensure that the collection within myclass never update
//while its doing following opetion
//Do somthing
}
finally
{
myclass.ReleaseLock();
}
}
}
现在这是对监视器的正确使用吗?我是否需要使用 Pulse 或 PulseAll 来发出等待线程的信号?如果需要,应该在退出函数之前或之后使用 plus 吗?
问候 穆巴沙尔
【问题讨论】:
-
除非您在一般线程方面的经验比在特定的 .NET 线程方面更有经验,否则我会认真重新考虑这样做,以便在不锁定的情况下更新集合。
标签: .net synchronization locking