每个静态方法都绝对需要锁定对象 [英] Is lock object deparatly necessary for every static methods
问题描述
排名:
请考虑以下代码:
public static class SomeClass
{
public static void Method1(string key, int item)
{
//Some Work
}
public static DataTable Method2()
{
//Some Work
}
....
如果从性能的角度来看,如果我想在Asp.Net应用程序中使用此类,是否需要为每个这样的方法使用单独的锁对象:
If I want to use this class in Asp.Net application from performance point of view does it need separate lock object for every methods like this:
public static class SomeClass
{
private Object thisLock1 = new Object();
public static void Method1(string key, int item)
{
lock(thisLock1)
{
//Some Work
}
}
private Object thisLock2 = new Object();
public static DataTable Method2()
{
lock(thisLock2)
{
//Some Work
}
}
....
推荐答案
每个静态方法绝对需要锁对象
Is lock object deparatly necessary for every static methods
没有,也没有
考虑这种情况
您还有另一个名为RemoveFromCache
的方法,它使用了lock3
You have another method called RemoveFromCache
and it uses lock3
线程1上的lock3
ItemRemove迭代开始
线程2上的lock1
项目已删除
thread1 Iterator.Next
lock3 on thread 1
ItemRemove Iteration Start
lock1 on thread 2
Item Removed
thread1 Iterator.Next
由于修改了集合,导致thread1发生异常.任何人都可以使用GetAllItems
方法获取集合的实例.用您的私人锁很难强制执行线程安全性.您应该考虑使用这些线程安全集合之一.
Exception on thread1 due to collection modified. Anyone can get an instance of the collection with GetAllItems
method. It is hard to enforce thread safety with your private lock. You should consider using one of those thread safe collection instead.
这篇关于每个静态方法都绝对需要锁定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!