如何使用system . web . cache。在控制台应用程序中缓存?

时间:2022-04-12 05:49:59

Context: .Net 3.5, C#
I'd like to have caching mechanism in my Console application.
Instead of re-inventing the wheel, I'd like to use System.Web.Caching.Cache (and that's a final decision, I can't use other caching framework, don't ask why).
However, it looks like System.Web.Caching.Cache is supposed to run only in a valid HTTP context. My very simple snippet looks like this:

上下文:。net 3.5, c#我希望在我的控制台应用程序中有缓存机制。我想使用system . web . cache而不是从头开始。缓存(这是最后的决定,我不能使用其他缓存框架,不要问为什么)。但是,它看起来像system . web . 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);
}

and the result is:

结果是:

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()

So obviously, I'm doing something wrong here. Any ideas?

显然,我做错了。什么好主意吗?


Update: +1 to most answers, getting the cache via static methods is the correct usage, namely HttpRuntime.Cache and HttpContext.Current.Cache. Thank you all!

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

6 个解决方案

#1


56  

The documentation for the Cache constructor says that it is for internal use only. To get your Cache object, call HttpRuntime.Cache rather than creating an instance via the constructor.

缓存构造函数的文档说,它仅供内部使用。要获取缓存对象,请调用HttpRuntime。缓存而不是通过构造函数创建实例。

#2


28  

While the OP specified v3.5, the question was asked before v4 was released. To help anyone who finds this question and can live with a v4 dependency, the framework team created a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace: http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

当OP指定v3.5时,这个问题在v4发布之前被提出。为了帮助任何发现这个问题并能够使用v4依赖的人,框架团队为这种场景创建了一个新的通用缓存。它在System.Runtime。缓存名称空间:http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

The static reference to the default cache instance is: MemoryCache.Default

默认缓存实例的静态引用是:MemoryCache.Default。

#3


9  

Just use the Caching Application Block if you don't want to reinvent the wheel. If you still want to use the ASP.NET cache- see here. I'm pretty sure this only works with .NET 2.0 and above though. It simply wasn't possible to use the cache outside of ASP.NET in .NET 1.

如果您不想重新发明*,只需使用缓存应用程序块。如果你还想使用ASP。网络缓存——在这里看到。我很确定这只适用于。net 2.0及以上版本。在ASP之外使用缓存是不可能的。净在。NET 1。

MSDN has a nice big warning on the page for the cache documentation too:

MSDN在页面上对缓存文档也有一个很好的警告:

The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.

缓存类不打算在ASP之外使用。网络应用程序。设计并测试了该算法在ASP中的应用。NET为Web应用程序提供缓存。在其他类型的应用程序中,如控制台应用程序或Windows窗体应用程序,ASP。NET缓存可能不能正常工作。

For a very lightweight solution, where you don't have to worry about expiration etc, then a dictionary object could suffice.

对于一个非常轻量级的解决方案,您不必担心过期等等,那么dictionary对象就足够了。

#4


4  

I ended on this page wondering the same thing. Here's what I'm doing (which I don't like but seems to work just fine):

我在这一页结束时也在想同样的事情。以下是我正在做的事情(我不喜欢,但似乎效果不错):

HttpContext context = HttpContext.Current;
if (context == null)
{
    HttpRequest request = new HttpRequest(string.Empty, "http://tempuri.org", string.Empty);
    HttpResponse response = new HttpResponse(new StreamWriter(new MemoryStream()));
    context = new HttpContext(request, response);
    HttpContext.Current = context;
}
this.cache = context.Cache;

#5


1  

Try

试一试

public class AspnetDataCache : IDataCache
{
    private readonly Cache _cache;

    public AspnetDataCache(Cache cache)
    {
        _cache = cache;
    }

    public AspnetDataCache()
        : this(HttpRuntime.Cache)
    {

    }
    public void Put(string key, object obj, TimeSpan expireNext)
    {
        if (key == null || obj == null)
            return;
        _cache.Insert(key, obj, null, DateTime.Now.Add(expireNext), TimeSpan.Zero);
    }

    public object Get(string key)
    {
        return _cache.Get(key);
    }

#6


1  

The System.Web.Caching.Cache class relies on having its member "_cacheInternal" set by the HttpRuntime object.

System.Web.Caching。缓存类依赖于由HttpRuntime对象设置其成员“_cacheInternal”。

To use the System.Web.Caching classes you'd have to create an HttpRuntime object and setup the HttpRuntime.Cache property. You'd effectively have to emulate IIS.

使用包含。必须创建一个HttpRuntime对象并设置HttpRuntime作为缓存类。缓存属性。实际上,您必须模拟IIS。

You're better off using other caching frameworks like:

最好使用其他缓存框架,如:

#1


56  

The documentation for the Cache constructor says that it is for internal use only. To get your Cache object, call HttpRuntime.Cache rather than creating an instance via the constructor.

缓存构造函数的文档说,它仅供内部使用。要获取缓存对象,请调用HttpRuntime。缓存而不是通过构造函数创建实例。

#2


28  

While the OP specified v3.5, the question was asked before v4 was released. To help anyone who finds this question and can live with a v4 dependency, the framework team created a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace: http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

当OP指定v3.5时,这个问题在v4发布之前被提出。为了帮助任何发现这个问题并能够使用v4依赖的人,框架团队为这种场景创建了一个新的通用缓存。它在System.Runtime。缓存名称空间:http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

The static reference to the default cache instance is: MemoryCache.Default

默认缓存实例的静态引用是:MemoryCache.Default。

#3


9  

Just use the Caching Application Block if you don't want to reinvent the wheel. If you still want to use the ASP.NET cache- see here. I'm pretty sure this only works with .NET 2.0 and above though. It simply wasn't possible to use the cache outside of ASP.NET in .NET 1.

如果您不想重新发明*,只需使用缓存应用程序块。如果你还想使用ASP。网络缓存——在这里看到。我很确定这只适用于。net 2.0及以上版本。在ASP之外使用缓存是不可能的。净在。NET 1。

MSDN has a nice big warning on the page for the cache documentation too:

MSDN在页面上对缓存文档也有一个很好的警告:

The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.

缓存类不打算在ASP之外使用。网络应用程序。设计并测试了该算法在ASP中的应用。NET为Web应用程序提供缓存。在其他类型的应用程序中,如控制台应用程序或Windows窗体应用程序,ASP。NET缓存可能不能正常工作。

For a very lightweight solution, where you don't have to worry about expiration etc, then a dictionary object could suffice.

对于一个非常轻量级的解决方案,您不必担心过期等等,那么dictionary对象就足够了。

#4


4  

I ended on this page wondering the same thing. Here's what I'm doing (which I don't like but seems to work just fine):

我在这一页结束时也在想同样的事情。以下是我正在做的事情(我不喜欢,但似乎效果不错):

HttpContext context = HttpContext.Current;
if (context == null)
{
    HttpRequest request = new HttpRequest(string.Empty, "http://tempuri.org", string.Empty);
    HttpResponse response = new HttpResponse(new StreamWriter(new MemoryStream()));
    context = new HttpContext(request, response);
    HttpContext.Current = context;
}
this.cache = context.Cache;

#5


1  

Try

试一试

public class AspnetDataCache : IDataCache
{
    private readonly Cache _cache;

    public AspnetDataCache(Cache cache)
    {
        _cache = cache;
    }

    public AspnetDataCache()
        : this(HttpRuntime.Cache)
    {

    }
    public void Put(string key, object obj, TimeSpan expireNext)
    {
        if (key == null || obj == null)
            return;
        _cache.Insert(key, obj, null, DateTime.Now.Add(expireNext), TimeSpan.Zero);
    }

    public object Get(string key)
    {
        return _cache.Get(key);
    }

#6


1  

The System.Web.Caching.Cache class relies on having its member "_cacheInternal" set by the HttpRuntime object.

System.Web.Caching。缓存类依赖于由HttpRuntime对象设置其成员“_cacheInternal”。

To use the System.Web.Caching classes you'd have to create an HttpRuntime object and setup the HttpRuntime.Cache property. You'd effectively have to emulate IIS.

使用包含。必须创建一个HttpRuntime对象并设置HttpRuntime作为缓存类。缓存属性。实际上,您必须模拟IIS。

You're better off using other caching frameworks like:

最好使用其他缓存框架,如: