【问题标题】:how to add multiple different data into MemoryCache如何将多个不同的数据添加到 MemoryCache
【发布时间】:2014-04-03 12:06:44
【问题描述】:

尽管我浏览了很多关于这个概念的文档,但我无法在这个问题上取得任何进展。我有一个 wcf 服务,它对 Sql Server 数据库进行一些查询。当我只缓存一个查询时,它按预期工作,但是当我尝试缓存两个查询时,第二个查询会引发异常The method has already been invoked。我是这个缓存的新手,所以让我知道我的缓存概念是否存在次要或主要的方法问题。下面是我正在尝试做的代码 sn-p:

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 方法,仍然是同样的异常。

【问题讨论】:

    标签: c# sql wcf caching memorycache


    【解决方案1】:

    每个缓存项都需要一个 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 中使用 * 并且你必须在表上指定所有者。所以

    SELECT * FROM Table1 
    

    变成

    SELECT Column1, Column1 FROM dbo.Table1
    

    详情请见here

    希望对你有帮助

    【讨论】:

    • 有道理,让我试试这个,然后我可以接受你的回答。我把这些查询作为示例,我实际上使用写在 sql server 中的函数来发出我的请求,它们里面没有任何 *。不过还是谢谢你的建议。
    猜你喜欢
    • 2014-06-18
    • 2019-11-06
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多