views:

1566

answers:

4

i try to put a lock to a static string object to access to cache,, the lock() block executes in my local,but whenever i deploy it to the server, it locks forever. i write every single step to event log to see the process and lock(object) just causes the deadlock on the server. The command right after lock() is never executed as the i dont see an entry in the event log. below is the code:

public static string CacheSyncObject = "CacheSync";
public static DataView GetUsers()
{

    DataTable dtUsers = null;
    if (HttpContext.Current.Cache["dtUsers"] != null)
    {
        Global.eventLogger.Write(String.Format("GetUsers() cache hit: {0}",dtUsers.Rows.Count));
        return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
    }

    Global.eventLogger.Write("GetUsers() cache miss");
    lock (CacheSyncObject)
    {
        Global.eventLogger.Write("GetUsers() locked SyncObject");

        if (HttpContext.Current.Cache["dtUsers"] != null)
        {
            Global.eventLogger.Write("GetUsers() opps, another thread filled the cache, release lock");
            return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
        }

Global.eventLogger.Write("GetUsers() locked SyncObject"); ==> this is never written to the log, so which means to me that, lock() never executes.

+4  A: 

What happens if you use:

public static object CacheSyncObject = new object();
Sunny
+1, try using an object instead of a string.
Samuel
+6  A: 

You're locking on a string, which is a generally bad idea in .NET due to interning. The .NET runtime actually stores all identical literal strings only once, so you have little control over who sees a specific string.

I'm not sure how the ASP.NET runtime handles this, but the regular .NET runtime actually uses interning for the entire process which means that interned strings are shared even between different AppDomains. Thus you could be deadlocking between different instances of you method.

Brian Rasmussen
A: 

That is the answer :) thanx all if i use an object, everything works fine.

A: 

There's a similiar question/answer over here on Stackoverflow

What is the best way to lock cache in asp.net?

AndrewDotHay