Is lock object deparatly necessary for every static methods [duplicate]

不想你离开。 提交于 2019-12-26 10:05:40

问题


Raleted to:

Lock in static methods

lock Statement

please consider this code:

public static class SomeClass
{
    public static void Method1(string key, int item)
    {
        //Some Work
    }

    public static DataTable Method2()
    {
        //Some Work
    } 

....

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
        }
    } 

....

回答1:


You don't HAVE to lock the object when you try to access it, but it's highly recommended.

If you don't want to perform these locks yourself, Microsoft added a class that's thread safe, it's the ConcurrentBag Class, it's great because this logic is already implemented, so you can access and remove it from several threads or classes.

However, locks give you a finer control over list access. Check this link for examples of bag implementation.




回答2:


Is lock object deparatly necessary for every static methods

NO, and NO

consider this case

You have another method called RemoveFromCache and it uses lock3

lock3 on thread 1
ItemRemove Iteration Start
lock1 on thread 2
Item Removed
thread1 Iterator.Next

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.



来源:https://stackoverflow.com/questions/47944037/is-lock-object-deparatly-necessary-for-every-static-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!