Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written the following two simple functions for storing some data in System.Runtime.Caching.MemoryCache and retrieving the same. I first call the first method and then in the immediate next statement, I call the second. It works fine when I do this in a simple Unit Test. But when I place the code in a WCF, call to the second method (GetFromCache) behaves inconsistently. Some times it return null and sometimes it returns the data from the cache.
(The Application Pool of WCF has been configured to use at-most one worker-process).
Please suggest.


C#
public virtual void FillAndMonitorCache(List<string> sqlListToBeMonitored, string cacheKey, object dataToBeCached)
{
    var policy = new CacheItemPolicy();

    SqlDependency.Start(_varianSystemConnectionString);

    using (var connection = new SqlConnection(_varianSystemConnectionString))
    {
        foreach (var sqlToBeMonitored in sqlListToBeMonitored)
        {
            using (var command = new SqlCommand(sqlToBeMonitored, connection))
            {
                command.Notification = null;
                var dependency = new SqlDependency();
                dependency.AddCommandDependency(command);
                connection.Open();
                command.ExecuteScalar();
                connection.Close();
                var monitor = new SqlChangeMonitor(dependency);
                policy.ChangeMonitors.Add(monitor);
            }
        }
    }

    MemoryCache.Default.Add(cacheKey, dataToBeCached, policy);
}

public virtual object GetFromCache(string cacheKey)
{
    return MemoryCache.Default[cacheKey];
}
Posted
Comments
Mehdi Gholam 4-May-15 1:11am    
Add logs to your code and see what is happening at runtime.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900