Reputation: 6301
I have an ASP.NET MVC app written in C#. One of my actions looks like this:
[HttpPost]
public async Task<ActionResult> Save(int id, MyViewModel viewModel)
{
viewModel.SaveToDb();
await Backup.Save(viewModel);
return View(viewModel);
}
...
public class Backup
{
async public static Task Save(IBackup item)
{
// do stuff
}
}
There is actually a lot going on in the Backup.Save function. In fact, await Backup.Save(...)
is currently taking 10 seconds. For that reason, I want to run it in the background (asynchronously) and not (a)wait on it. I thought if I just removed the await
keyword, it would work. However, it does not appear that is the case.
How can I run Backup does save asynchronously in the background so that my users can continue using the app without long wait times?
Thank you!
Upvotes: 0
Views: 189
Reputation: 631
See here for a discussion of this: Can I use threads to carry out long-running jobs on IIS?
One simple alternative without having to use threads or queues would be to make an additional async call via the client, possibly via Ajax assuming the client is a browser.
If you need the view model back immediately, then potentially split this into two methods. One that gets the view model, and then you call a second method that does the save in the background.
This should work fine since if you are happy to return right away, you have already implicitly agreed to decoupled the dependency between the two actions.
It is a bit of a hack, since the client is now requesting an action it may not need to know or care about.
Upvotes: 2
Reputation: 1300
you can make a method that takes an action or a function (whatever you need), and runs a thread with whatever you need to run in the background.
Basically whatever way you choose to make it, run the method in a separate thread.
Upvotes: 0