Primary issue: There's a block of code that I want to execute in the background. Please read further to understand what I mean by "background".
I am trying to perform external data posting through a an asynchronous/non-blocking thread. The main idea is that the user who submits the form need not wait for the external requests to complete.
The current flow is like this:
- User submits a form, with data
- Action processes the data performs internal steps like database updates, email notifications etc, and also uses external resources to post data using API
- User is taken to the "thank you page"
I am trying to decouple the UploadFilesToAmazonAWSAndDropBoxAndFlickrAndGoogleDrive
from the regular user flow, as in the current setup, the user is waiting for the external API to complete. How to make UploadFilesToAmazonAWSAndDropBoxAndFlickrAndGoogleDrive
run in a background thread?
Edit: Posting a rough outline of the code that I am trying to fix
[HttpPost]
public ActionResult Index(FormCollection fc)
{
//database operations,
InsertIntoDatabase(fc); //takes 1 second
//3rd party posting
//Takes about 30 seconds.
//Why it takes 30 seconds is obvious. Please let me know if this isn't obvious.
UploadFilesToAmazonAWSAndDropBoxAndFlickrAndGoogleDrive(fc);
//email operations
SendEmails(fc); //takes 1 second
//User is taken to Thank you page after 32 seconds. I want to reduce the time to 2 seconds
return View("ThankYou");
}
CodePudding user response:
Based on your edited scenario and target, the following high-level options might work to get you there.
- You could use Task.Run to start a background thread for your
PostDataToExternalResources
method, but you will still need to manage any exceptions etc on your side. Additionally, I wouldn't pass the form collection off to that method if you do it this way, just keep in mind that you wouldn't have guaranteed results - You could use something like HangFire to turn that process into a background job, which has its own durability etc. I again wouldn't pass the FormCollection in, but it could have better durability.
Since it seems that viewing the "Thank you" page is not dependent upon the tasks completing, I'd look at something durable/executable like HangFire for consistency and ease of management