如何将多个不同的数据添加到MemoryCache中

时间:2014-04-03 12:06:44

标签: c# sql wcf caching memorycache

尽管我查看了很多关于这个概念的文件,但我无法在这个问题上取得任何进展。我有一个wcf服务,它对Sql Server数据库进行一些查询。当我只缓存一个查询时它按预期工作,但是当我尝试缓存两个查询时,第二个查询抛出异常The method has already been invoked。我是这个缓存内容的新手,所以让我知道我的cachce概念是否有一个小的或重大的方法问题。以下是我尝试做的代码片段:

var cachePolicy = new CacheItemPolicy();
var cache = MemoryCache.Default;

firstObject = cache["firstObject"] as string;
if ( firstObject == null )
    using ( var command = new SqlCommand("SELECT * FROM someTable", connection) )
    {
        cachePolicy.ChangeMonitors.Add(new SqlChangeMonitor(new SqlDependency(command, null, 600)));
        ///... I get the data from database and set the firstObject
        cache.Add("firstObject", firstObject , cachePolicy);
    }

secondObject = cache["secondObject"] as string;
if ( secondObject == null )
    using ( var command = new SqlCommand("SELECT * FROM someTable2", connection) )
    {
        cachePolicy.ChangeMonitors.Add(new SqlChangeMonitor(new SqlDependency(command, null, 600)));
        ///... I get the data from database and set the secondObject 
        cache.Add("secondObject", secondObject , cachePolicy);///---> problem occurs here
    }

我也尝试使用cache.Set方法,但仍然是同样的异常。

1 个答案:

答案 0 :(得分:2)

每个缓存项需要一个CacheItemPolicy,因此您的代码应该更像:

var cache = MemoryCache.Default;

var firstObject = cache["firstObject"] as string;
if (firstObject == null)
{
    var cmd = new SqlCommand("SELECT * FROM Table1");
    firstObject = GetFirstObject(cmd);
    var policy = new CacheItemPolicy();
    policy.ChangeMonitors.Add(new SqlChangeMonitor(new SqlDependency(cmd, null, 600)));
    cache.Add("firstObject", firstObject, policy);
}

var secondObject = cache["secondObject"] as string;
if (secondObject == null)
{
    var cmd = new SqlCommand("SELECT * FORM Table2");
    secondObject = GetSecondObject(cmd);
    var policy = new CacheItemPolicy();
    policy.ChangeMonitors.Add(new SqlChangeMonitor(new SqlDependency(cmd, null, 600)));
    cache.Add("secondObject", secondObject, policy);
}

另外,我认为你会发现使用SqlDependency你不能在select中使用*,你必须在表上指定owner。所以

SELECT * FROM Table1 

成为

SELECT Column1, Column1 FROM dbo.Table1

有关详细信息,请参阅here

希望这有帮助