Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 924
user2873833 Avatar asked Oct 12 '13 11:10

user2873833


People also ask

What happens if you don't await a Task?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.

Does Task run need to be awaited?

If it is some trivial operation that executes quickly, then you can just call it synchronously, without the need for await . But if it is a long-running operation, you may need to find a way to make it asynchronous.

What is Task delay?

The Delay method is typically used to delay the operation of all or part of a task for a specified time interval. Most commonly, the time delay is introduced: At the beginning of the task, as the following example shows.

What is Task wait?

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread.


2 Answers

public class HomeController : Controller
{
  public ActionResult Index()
  {
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    Task.Run(()=> DoSomeAsyncStuff());

    return View();
  }

  private async void DoSomeAsyncStuff()
  {

  }
}
like image 144
Oliver Weichhold Avatar answered Oct 25 '22 08:10

Oliver Weichhold


For .NET Core I use this

_ = Task.Run(() => SomeAsyncFunction());
like image 21
Ron Michael Avatar answered Oct 25 '22 08:10

Ron Michael