You can do that if RunAsync
is making I/O requests, but you wouldn't return a Task
:
[HttpPost("run")]
public object Run([FromBody] ResearchRequest researchRequest)
{
researchService.RunAsync(researchRequest);
return new{ queued = true };
}
That will start running RunAsync
on the same thread, just like any other method. At the first await
in RunAsync
that acts on an incomplete Task
, RunAsync
will return its own incomplete Task
, at which point control returns back to your Run
action and your object
is returned. You won't be waiting for whatever I/O operation RunAsync
makes.
If RunAsync
is taking a long time because of CPU calculations (not I/O), then that won't do anything for you because, remember, it starts running on the same thread. You will have to start it on another thread, which you can do using Task.Run
:
[HttpPost("run")]
public Task<object> Run([FromBody] ResearchRequest researchRequest)
{
Task.Run(() => researchService.RunAsync(researchRequest));
return new{ queued = true };
}
But!
In both cases, ASP.NET will have no idea that RunAsync
is running in the background. If the IIS app pool is shut down or recycled for any reason, that job will be killed part way through. Note that by default, IIS is configured to shut down an app pool after 20 minutes of no HTTP requests coming in.
If that is unacceptable to you, then you're better off writing the job to a queue in a database or something and doing that background processing in a Windows service.