Javascript同时调用异步端点

时间:2016-08-24 12:10:53

标签: c# .net ajax multithreading asynchronous

我正在尝试实现异步端点(.NET C#),以便使用javascript / ajax调用它们。基本思想是在多个线程中分割请求(> 2),以便用户从每次调用中单独获得响应,并且每个请求的执行时间对应于实际计算(或等待)时间。

public async Task<ActionResult> Call1()
{
    var client = new HttpClient();
    var res = await client.GetAsync("http://httpbin.org/delay/3"); // Takes 3 seconds

    return View("~/Views/Dashboard/Test.cshtml");
}

public async Task<ActionResult> Call2()
{
    var client = new HttpClient();
    var res = await client.GetAsync("http://httpbin.org/delay/2"); // Takes 2 seconds

    return View("~/Views/Dashboard/Test.cshtml");
}

假设浏览器同时请求方法Call1和Call2。现在大约需要5秒才能完成两个呼叫终止(Call1(3sec)+ Call2(2sec))。据我所知,这意味着.NET处理它们是同步的,并在处理Call2之前等待Call1结束,尽管它们是用异步方法同时调用的。那不是我想要的。

request times call1 / call2

我希望使用多种方法获得相同的结果,如下面的方法所示,虽然两种服务(3秒+ 2秒)都被调用,但只需要3秒钟:

public async Task<ActionResult> Delay()
{
    var client1 = new HttpClient();
    Task<HttpResponseMessage> async1 = client1.GetAsync("http://httpbin.org/delay/3");

    var client2 = new HttpClient();
    Task<HttpResponseMessage> async2 = client2.GetAsync("http://httpbin.org/delay/2");

    HttpResponseMessage result1 = await async1;
    HttpResponseMessage result2 = await async2;

    return View("~/Views/Dashboard/Test.cshtml");
}

是否有可能不阻止其他线程并同时处理多个方法?

感谢您的帮助。 VILL

1 个答案:

答案 0 :(得分:0)

需要5秒的原因是因为您先等待result1然后再等待result2。尝试并修改代码以创建任务列表,然后使用Task.WhenAll等待所有任务。详细了解Task.WhenAll here

public async Task<ActionResult> Delay()
{
    var tasks= new List<Task>();

    var client1 = new HttpClient();
    tasks.Add(client1.GetAsync("http://httpbin.org/delay/3"));

    var client2 = new HttpClient();
    tasks.Add(client2.GetAsync("http://httpbin.org/delay/3"));

    await Task.WhenAll(tasks);

    return View("~/Views/Dashboard/Test.cshtml");

}