正确的方式进行异步调用

时间:2013-03-15 19:57:52

标签: c# .net asp.net-mvc asynchronous

我的情况是可扩展性至关重要。我有一个API端点,它必须调用第三方Web服务,可能需要10秒以上才能完成。我关心的是在等待第三方请求完成时,Web请求堆叠在我们的服务器上。我需要确保“StartJob”的请求立即返回,并且作业实际上在后台运行。最好的方法是什么?

// 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();
}

1 个答案:

答案 0 :(得分:3)

如果来电者不关心结果,你可以这样做:

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

你也可以按照this comment中的Servy的建议使用这种改编。

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