ASP.NET Core Background task with service container

13 views Asked by At

In an ASP.NET Core Web API project, I use Task.Run to trigger a long running operation.

Here is the code:

[HttpPost("endpoint1")]
public ActionResult Endpoint1()
{
    _ = Task.Run(async () => 
    {
        // create a new IoC container from scratch
        // do some long running operation using the services from the container
    });
    return Ok();
}

I would have a few question to it:

  1. Will the running task not be disposed while it is running since there is no reference to it? Is it safe in this regard?
  2. Inside the Run method I create a new IoC container containing services from scratch. Would there be a better alternative that would solve this issue?
0

There are 0 answers