我想询问一些关于在.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来通知等待线程,如果需要的话,Exit函数应该在之前还是之后执行?
谢谢 Mubashar