I am using asp.net mvc and I want to cache some data about user from database when he reaches the home page of the site. So when user requests the Home page, I want to call an async method, which makes database calls and caches data.
Any examples of doing this would be great.
4 Answers
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
Task.Run(()=> DoSomeAsyncStuff());
return View();
}
private async void DoSomeAsyncStuff()
{
}
}
For .NET Core I use this
_ = Task.Run(() => SomeAsyncFunction());
I would say you call the caching method via this:
HostingEnvironment.QueueBackgroundWorkItem(x=> CacheData());
In that way, you don't really keep the home page request waiting so the users get to see the home page immediately, while the caching happens in the background at the server.
PS: But yes you run a slight risk of app domain recycling screwing up your caching thread.
ThreadPool.QueueUserWorkItem((Action<object>)state =>
{
//do your async work
}, null);
or Task.StartNew(...)
(sorry for the brief answer, this may take you on the right track or someone can edit this to show a full example, please?)