Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# dotnet内核中的内存缓存_C#_Caching_.net Core_Memorycache - Fatal编程技术网

C# dotnet内核中的内存缓存

C# dotnet内核中的内存缓存,c#,caching,.net-core,memorycache,C#,Caching,.net Core,Memorycache,我正在尝试编写一个类来处理.net核心类库中的内存缓存。如果我不使用核心,那么我可以写 using System.Runtime.Caching; using System.Collections.Concurrent; namespace n{ public class MyCache { readonly MemoryCache _cache; readonly Func<CacheItemPolicy> _cachePolicy;

我正在尝试编写一个类来处理.net核心类库中的内存缓存。如果我不使用核心,那么我可以写

using System.Runtime.Caching;
using System.Collections.Concurrent;

namespace n{
public class MyCache
{
        readonly MemoryCache _cache;
        readonly Func<CacheItemPolicy> _cachePolicy;
        static readonly ConcurrentDictionary<string, object> _theLock = new ConcurrentDictionary<string, object>();

        public MyCache(){
            _cache = MemoryCache.Default;
            _cachePolicy = () => new CacheItemPolicy
            {
                SlidingExpiration = TimeSpan.FromMinutes(15),
                RemovedCallback = x =>    
                {
                    object o;
                    _theLock.TryRemove(x.CacheItem.Key, out o);
                }
            };
        }
        public void Save(string idstring, object value){
                lock (_locks.GetOrAdd(idstring, _ => new object()))
                {
                        _cache.Add(idstring, value, _cachePolicy.Invoke());
                }
                ....
        }
}
}
建造商是:

using Microsoft.Extensions.Caching.Memory;
。 .

我的回答集中在“在.Net内核中,我找不到System.Runtime.Cache”,因为我遇到了同样的问题。对于将
IMemoryCache
用于特定OP的场景,公认的答案非常好


有两种完全不同的缓存实现/解决方案:

1-
System.Runtime.Caching/MemoryCache

2-
Microsoft.Extensions.Caching.Memory/IMemoryCache


System.Runtime.Caching/MemoryCache:
这与以前的ASP.NETMVC的
HttpRuntime.Cache
非常相似您可以在ASP.Net CORE上使用它,而无需任何依赖项注入。以下是如何使用它:

// First install 'System.Runtime.Caching' (NuGet package)

// Add a using
using System.Runtime.Caching;

// To get a value
var myString = MemoryCache.Default["itemCacheKey"];

// To store a value
MemoryCache.Default["itemCacheKey"] = myString;

Microsoft.Extensions.Caching.Memory
这一个与依赖注入紧密耦合。这是实现它的一种方法:

// In asp.net core's Startup add this:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}
在控制器上使用它:

// Add a using
using Microsoft.Extensions.Caching.Memory;

// In your controller's constructor, you add the dependency on the 'IMemoryCache'
public class HomeController : Controller
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public void Test()
    {
        // To get a value
        string myString = null;
        if (_cache.TryGetValue("itemCacheKey", out myString))
        { /*  key/value found  -  myString has the key cache's value*/  }


        // To store a value
        _cache.Set("itemCacheKey", myString);
    }
}


正如@WillC所指出的,这个答案实际上是一个文档摘要。您可以在那里找到扩展信息。

如果您使用Asp.net core,则无需为缓存自定义单例,因为您的缓存类支持Asp.net core

要使用IMemoryCache将数据设置到服务器的内存中,可以执行以下操作:

public void Add<T>(T o, string key)
{
    if (IsEnableCache)
    {
        T cacheEntry;

        // Look for cache key.
        if (!_cache.TryGetValue(key, out cacheEntry))
        {
            // Key not in cache, so get data.
            cacheEntry = o;

            // Set cache options.
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                // Keep in cache for this time, reset time if accessed.
                .SetSlidingExpiration(TimeSpan.FromSeconds(7200));

            // Save data in cache.
            _cache.Set(key, cacheEntry, cacheEntryOptions);
        }
    }
}
public void Add(to,字符串键)
{
如果(IsEnableCache)
{
纪念印;
//查找缓存密钥。
if(!\u cache.TryGetValue(键,out cacheEntry))
{
//密钥不在缓存中,因此获取数据。
cacheEntry=o;
//设置缓存选项。
var cacheEntryOptions=new MemoryCacheEntryOptions()
//在缓存中保留此时间,如果访问,则重置时间。
.SetSlidingExpiration(时间跨度从秒开始(7200));
//将数据保存在缓存中。
_Set(key、cacheEntry、cacheEntryOptions);
}
}
}
有关更多详细信息,请阅读文章

  • 通过构造函数注入MemoryCache(从nugget获取引用 Microsoft.Extensions.Caching.Memory
private只读IMemoryCache memoryCache;
  • 代码实现
private IList GetListFromCache()
{
const string Key=“employee”;
IList cacheValue=null;
如果(!this.memoryCache.TryGetValue(Key,out cacheValue))
{
////密钥不在缓存中,因此获取数据。
cacheValue=this.context.Employee.AsNoTracking().Include(x=>
x、 ToList();
////设置缓存选项。
var cacheEntryOptions=new MemoryCacheEntryOptions()
////在缓存中保留此时间,如果访问,则重置时间。
.SetSlidingExpiration(TimeSpan.from天(1));
////将数据保存在缓存中。
this.memoryCache.Set(Key、cacheValue、cacheEntryOptions);
}
返回缓存值;
}
在Startup.cs中的ConfigureServices下注册AddMemoryCache

services.AddMemoryCache();
  • 用于单元测试的模拟IMemoryCache
///获取内存缓存。
///内存缓存对象。
公共IMemoryCache GetMemoryCache()
{
var services=newservicecolection();
services.AddMemoryCache();
var serviceProvider=services.BuildServiceProvider();
返回serviceProvider.GetService();
}
//在构造函数中为单元测试注入内存缓存
this.memoryCache=text.GetMemoryCache();

在这种方法中,我们无法在NET标准库中实现内存缓存行为。您能告诉我如何将IMemorycache集成到网络标准库中吗?@Parthi请阅读此帖子:@mattinsalto如何设置内存缓存名称?谢谢您提供的信息。我正在将一些代码从.net移植到core,这很有用,因为这两个重叠的实现很容易混淆。我还找到了这个链接来扩展您在这里所说的内容@我很高兴这个答案对你有帮助!是的,您提供的链接实际上是我执行这些实现的源代码。我的答案有点像是你提供的相同文档中的“摘要”。“我认为这是没有必要的,但因为它与你有关,我会把它包括在我的答案中。”雷阳:好问题。这取决于一些因素:如果您已经在使用依赖项注入,那么您可以轻松地与其他依赖项一起实现
Microsoft.Extensions.Caching.Memory/IMemoryCache
。另外,如果您使用的是ASP.NETCore,那么使用DI是一种最佳实践。另一方面,如果您的使用是特定的、简单的和有限的,那么我认为使用
System.Runtime.Caching/MemoryCache
不会有任何设计问题。而且,后者对原型设计非常有帮助。@LeiYang说,这是一个设计方面。我想说的是,当问“我什么时候应该使用依赖注入”时,答案是一样的。我还应该提到,新的
Microsoft.Extensions.Caching.Memory/IMemoryCache
System.Runtime.Caching/MemoryCache
的“更新版”和当前版本,目前仅作为旧式解决方案受支持。因此,
IMemoryCache
具有更好的性能,但实际上在绝大多数情况下,性能差异是完全可以忽略的。
// In asp.net core's Startup add this:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}
// Add a using
using Microsoft.Extensions.Caching.Memory;

// In your controller's constructor, you add the dependency on the 'IMemoryCache'
public class HomeController : Controller
{
    private IMemoryCache _cache;
    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public void Test()
    {
        // To get a value
        string myString = null;
        if (_cache.TryGetValue("itemCacheKey", out myString))
        { /*  key/value found  -  myString has the key cache's value*/  }


        // To store a value
        _cache.Set("itemCacheKey", myString);
    }
}
public void Add<T>(T o, string key)
{
    if (IsEnableCache)
    {
        T cacheEntry;

        // Look for cache key.
        if (!_cache.TryGetValue(key, out cacheEntry))
        {
            // Key not in cache, so get data.
            cacheEntry = o;

            // Set cache options.
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                // Keep in cache for this time, reset time if accessed.
                .SetSlidingExpiration(TimeSpan.FromSeconds(7200));

            // Save data in cache.
            _cache.Set(key, cacheEntry, cacheEntryOptions);
        }
    }
}