musium
musium

Reputation: 3072

Background operations in ASP.NET MVC

In my ASP.NET MVC 5 application, I cache the results of long-running database queries using Redis as an LRU cache. Whenever the user requests such a result the application first checks if it is already cached... If it’s found in the cache the application will return the cached result. If not, the application will execute the query and then cache the result.

In a few cases it can happen that the application needs to write quite a lot of cache entries (>10000). Is there a way to immediately respond to the request of the user and write the cache in the background?

I was thinking about writing the cache in a fire and forget like manner making the method writing the cache async void. I do not care about any results of the method, it “doesn’t matter” if it fails or not or if it's completed before the next requests hits the application or not… (The application does not in any way depend on the cache entries being present.)

Is using async void in ASP.NET MVC a good idea or can it cause problems? If not, what would be the correct solution to write the cache without letting the user wait?

Upvotes: 0

Views: 1021

Answers (2)

sesispla
sesispla

Reputation: 300

Have a look to Hangfire:

"Hang fire: An easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications. No Windows Service required."

Upvotes: 3

Joseph Simpson
Joseph Simpson

Reputation: 4183

You can return void and use QueueBackgroundWorkItem to populate your cache.

QueueBackgroundWorkItem provides a safe way to run a short-lived background task.

Upvotes: 1

Related Questions