相关疑难解决方法(0)

如何在Console应用程序中使用System.Web.Caching.Cache?

上下文:.Net 3.5,C#
我想在我的控制台应用程序中使用缓存机制.
我想使用System.Web.Caching.Cache(而这是最后的决定,我不能使用其他缓存框架,不要问为什么),而不是重新发明轮子.
但是,它看起来System.Web.Caching.Cache应该只在有效的HTTP上下文中运行.我非常简单的代码片段如下所示:

using System;
using System.Web.Caching;
using System.Web;

Cache c = new Cache();

try
{
    c.Insert("a", 123);
}
catch (Exception ex)
{
    Console.WriteLine("cannot insert to cache, exception:");
    Console.WriteLine(ex);
}
Run Code Online (Sandbox Code Playgroud)

结果是:

cannot insert to cache, exception:
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.Caching.Cache.Insert(String key, Object value)
   at MyClass.RunSnippet()

显然,我在这里做错了.有任何想法吗?


更新:+1到大多数答案,通过静态方法获取缓存是正确的用法,即HttpRuntime.CacheHttpContext.Current.Cache.谢谢你们!

.net caching console-application httpcontext

29
推荐指数
3
解决办法
3万
查看次数

标签 统计

.net ×1

caching ×1

console-application ×1

httpcontext ×1