Start a Task Without Waiting

Start a Task Without Waiting

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.

1

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()
  {

  }
}
3

For .NET Core I use this

_ = Task.Run(() => SomeAsyncFunction());
1

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?)

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.