I am working in a multi-layered web application that has ASP.NET MVC as its front-end client. A particular page of this web application is taking a very long time to load. Around 30 seconds.
I downloaded dotTrace and ran it on my application (following this tutorial). I found out that the reason my application is slow.
It turns out it is because one particular method that I have does a load of work (takes time), and that same method gets called a total of 4 times.
Here is a screenshot from dotTrace showing the above:
The method in question is GetTasks()
. So in order to improve the speed of the web application I want to cache the data returned from GetTasks()
for each request.
If my thinking is correct, this would really improve on the speed issues I am having.
My question is, how can I achieve this? I have never done such a thing before. For each new request, how can I cache the data returned from GetTasks()
, and use that for all subsequent calls to GetTasks()
.
One of the most popsular solution is to cache results. I can shouw you my solution. First of all install Nuget package: LazyCache Then you can use wrapper that I've created wrapper: code. You can extract and interface or whatever.
Then you can use it like this:
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");
}