gpt4 book ai didi

.net - 使用监视器类

转载 作者:行者123 更新时间:2023-12-01 13:06:51 26 4
gpt4 key购买 nike

我想问几个关于在 .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();
}
}
}

现在这是 monitor 的正确使用吗?我是否需要使用 Pulse 或 PulseAll 来指示等待线程,如果是这样,应该在 Exit 函数之前或之后使用加号?

问候穆巴沙尔

最佳答案

是的,您对 Monitor 的使用是正确的。

也就是说,您可以使用lock 语句使代码更简洁:

public static void main(args)
{
lock(myclass)
{
}
}

关于.net - 使用监视器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2505575/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com