0

我正在使用 ASP.NET MVC 作为其前端客户端的多层 Web 应用程序。此 Web 应用程序的特定页面需要很长时间才能加载。大约30秒。

我下载了dotTrace并在我的应用程序上运行它(按照本教程)。我发现我的应用程序很慢的原因。

事实证明,这是因为我拥有的一种特定方法做了很多工作(需要时间),并且该方法总共被调用了 4 次。

这是来自 dotTrace 的屏幕截图,显示了上述内容:

dotTrace 截图

有问题的方法是GetTasks()。因此,为了提高 Web 应用程序的速度,我想缓存GetTasks()每个请求返回的数据。

如果我的想法是正确的,这将真正改善我遇到的速度问题。

我的问题是,我怎样才能做到这一点?我以前从来没有做过这样的事情。对于每个新请求,我如何缓存从返回的数据GetTasks(),并将其用于所有后续调用GetTasks()

4

2 回答 2

1

您是否考虑过Cache Aside 模式

您可以使用LazyCache轻松实现它

//probably in my constructor (or use dependency injection)
this.cache = new CachingService()

public List<MyTasks> GetTasks() 
{
    return cache.GetOrAdd<List<MyTasks>>("get-tasks", () = > {
        //go and get the tasks here.
    });
}

有关更多信息,请参阅https://alastaircrabtree.com/the-easy-way-to-add-caching-to-net-application-and-make-it-faster-is-call-lazycache/

于 2018-02-27T11:45:07.307 回答
0

最流行的解决方案之一是缓存结果。我可以告诉你我的解决方案。首先安装 Nuget 包:LazyCache 然后你可以使用我创建的包装器 wrapper: code。您可以提取和接口或其他任何东西。

然后你可以像这样使用它:

private readonly CacheManager cacheManager = new CacheManager(); 
          // or injected via ctor

public IEnumerable<Task> GetTasks()
{
    return this.cacheManager.Get("Tasks", ctx => this.taskRepository.GetAll());
}

public void AddTask(Task task)
{
    this.taskRepository.Create(task);
    /// other code

    // we need to tell the cache that it should get fresh collectiion
    this.cacheManager.Signal("Tasks"); 
}
于 2014-08-04T13:15:43.283 回答