I need your advise on using Task.Run()
in ASP.NET MVC async controller action. We currently have a time consuming backend SP that takes few minutes to execute when user clicks "Approve". User just need to approve and need not wait until this backend execution completes so we are using Task.Run
here as seen in the below code.
Earlier this was done by ThreadPool.QueueUserWorkItem()
so that it is done in the background. Now, we are migrating this app to ASP.Net MVC 5.0.
We tested this and its all working fine but we need to make sure if this will not create any problems in future. Please advise.
public async Task<ActionResult> ApprovePayments(int Id)
{
await (db.PaymentApprove(Id, User == null ? "" : User.Identity.Name));
Task.Run(() => {
DBModel dbReport = new DBModel();
dbReport.PaymentReportCreate(Id);
dbReport.Dispose();
});
SetUnapprovedPaymentsViewBag();
return View("PendingPayments");
}
We tested this and its all working fine but we need to make sure if this will not create any problems in future.
Yes, it certainly can cause problems because ASP.NET is not aware of your background work.
I describe a variety of approaches on my blog. The only reliable solution is to save the work to persistent storage and have an independent worker processing it. Hangfire is one such solution.
But if you're OK with occasionally losing work, then you can register the background work with HostingEnvironment.QueueBackgroundWorkItem
.
Under no circumstances should you use Task.Run
or ThreadPool.QueueUserWorkItem
to kick off background work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With