同时调用两个Web服务方法(并行) [英] Call two web service methods simultaneously(parallel)

查看:242
本文介绍了同时调用两个Web服务方法(并行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello All .......



我是.Net开发的新手..........



我想使用应用程序中的c#代码同时(并行)调用两个Web服务方法,Web服务是作为单独的应用程序构建的。在我的应用程序中,应该调用一个Web服务方法并且不需要等待响应,然后应该调用另一个服务方法并且不需要等待响应,但是在调用这两种服务方法之后,我需要等待第一种方法的响应并根据我需要继续进行的结果,执行此操作的最佳方法是什么?



提前致谢。



关注

Hello All.......

I am new in .Net development..........

I want to call two web service methods simultaneously(parallel) using c# code from the application, web service is built as a separate application. In my application, one web service method should get called & it is not needed to wait for the response, then another service method should get called & it is not needed to wait for the response, but after calling both of these service methods, I need to wait for the respond for first method & as per the result I need to proceed ahead, what is the best way to perform this?

Thanks in advance.

Regards

推荐答案

最简单的解决方案是使用HttpClient类然后进行异步调用并等待那些任务要完成。见下面的示例。



The simplest solution would be to use the HttpClient class then make async calls and wait for those tasks to complete. See sample below.

static void Run()
{
    //Follow steps at this link for addding a reference to the necessary .NET library:
    //http://stackoverflow.com/questions/9611316/system-net-http-missing-from-    
    //namespace-using-net-4-5

    //Create an HTTP Client
    var client = new HttpClient();

    //Call first service
    var task1 = client.GetAsync("http://www.cnn.com");

    //Call second service
    var task2 = client.GetAsync("http://www.google.com");

    //Create list of all returned async tasks
    var allTasks = new List<Task<HttpResponseMessage>> { task1, task2 };

    //Wait for all calls to return before proceeding
    Task.WaitAll(allTasks.ToArray());

}


好的建议(特别是在params附近)。通过试着清楚地说明......,我认为在不返回其他任务方面保持简单会使事情变得更容易理解。



如果我从这个方法返回一个Task,我会把它变成泛型并返回一个HttpResponseMessages数组:





Good recommendations (especially around the params). With the "try to tell it clearly...", I thought that keeping it simple in terms of not returning another task would make things simpler to understand.

If I were to return a Task from this method I would make it generic and return an array of HttpResponseMessages:


static Task<HttpResponseMessage[]> Run()
{
    ...
    return Task.WhenAll(task1, task2);
}


这篇关于同时调用两个Web服务方法(并行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆