How to use MemoryCache in C# Core Console app?(如何在C#核心控制台应用程序中使用内存缓存?)
本文介绍了如何在C#核心控制台应用程序中使用内存缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在.NET Core2.0控制台应用程序中使用Microsoft.Extensions.Caching.Memory.MemoryCache(实际上,在控制台或ASP.NET应用程序中使用的库中)
我已创建测试应用:
using System;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
int count = cache.Count;
cache.CreateEntry("item1").Value = 1;
int count2 = cache.Count;
cache.TryGetValue("item1", out object item1);
int count3 = cache.Count;
cache.TryGetValue("item2", out object item2);
int count4 = cache.Count;
Console.WriteLine("Hello World!");
}
}
}
不幸的是,这不起作用。这些项目不会添加到缓存中,并且无法检索。
我怀疑我需要使用DependencyInjection,执行如下操作:
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
var provider = new Microsoft.Extensions.DependencyInjection.ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();
//And now?
var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
var xxx = PSP.Helpers.DependencyInjection.ServiceProvider;
int count = cache.Count;
cache.CreateEntry("item1").Value = 1;
int count2 = cache.Count;
cache.TryGetValue("item1", out object item1);
int count3 = cache.Count;
cache.TryGetValue("item2", out object item2);
int count4 = cache.Count;
Console.WriteLine("Hello World!");
}
}
}
不幸的是,这也不起作用,我怀疑我不应该创建新的内存缓存,而是从服务提供商那里获得它,但一直无法做到这一点。
有什么想法吗?
推荐答案
配置提供程序后,通过GetService扩展方法检索缓存
var provider = new ServiceCollection()
.AddMemoryCache()
.BuildServiceProvider();
//And now?
var cache = provider.GetService<IMemoryCache>();
//...other code removed for brevity;
来自评论:
不需要使用依赖注入,唯一需要做的就是处理CreateEntry()的返回值。 需要释放
CreateEntry返回的条目。在……上面 Dispose,则将其添加到缓存:
using (var entry = cache.CreateEntry("item2")) {
entry.Value = 2;
entry.AbsoluteExpiration = DateTime.UtcNow.AddDays(1);
}
这篇关于如何在C#核心控制台应用程序中使用内存缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在C#核心控制台应用程序中使用内存缓存?
基础教程推荐
猜你喜欢
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
