Micah
Micah

Reputation: 116050

Proper way to make an async call

I have a situation where scalability is of utmost importance. I have an API endpoint which has to make a call to a 3rd party web service and it could take over 10 seconds to complete. What I'm concerned about is web requests stacking up on our server while waiting for the 3rd party requests to complete. I need to make sure that the requests to "StartJob" return immediately and the job actually runs in the background. What's the best way to do this?

// Client polls this endpoint to find out if job is complete
public ActionResult GetResults(int jobId)
{
    return Content(Job.GetById(jobId));
}

//Client kicks off job with this endpoint
public ActionResult StartJob()
{
    //Create a new job record
    var job = new Job();
    job.Save();

    //start the job on a background thread and let IIS return it's current thread immediately
    StartJob(); //????

    return Content(job.Id);
}

//The job consists of calling a 3rd party web service which could take 10+ seconds.
private void StartJob(long jobId)
{
   var client = new WebClient();
   var response = client.downloadString("http://some3rdparty.com/dostuff");

   var job = Job.GetById(jobId);
   job.isComplete = true;
   job.Save();
}

Upvotes: 0

Views: 139

Answers (1)

Alex Tsvetkov
Alex Tsvetkov

Reputation: 1659

If the caller doesn't care for the result you can do something like this:

Task.Factory.StartNew(StartJob(job.Id));

You could also use this adaptation as suggested by Servy in this comment.

Task.Factory.StartNew(StartJob(job.Id), TaskCreationOptions.LongRunning);

Upvotes: 3

Related Questions