2009-11-03 42 views
4

在Visual Studio我创建了一个Web服务(并检查 “生成异步操作”)在这个网址:如何异步调用此webservice?

http://www.webservicex.com/globalweather.asmx

和可以得到的数据出来同步但什么是异步获取数据的语法

using System.Windows; 
using TestConsume2343.ServiceReference1; 
using System; 
using System.Net; 

namespace TestConsume2343 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 

      GlobalWeatherSoapClient client = new GlobalWeatherSoapClient(); 

      //synchronous 
      string getWeatherResult = client.GetWeather("Berlin", "Germany"); 
      Console.WriteLine("Get Weather Result: " + getWeatherResult); //works 

      //asynchronous 
      client.BeginGetWeather("Berlin", "Germany", new AsyncCallback(GotWeather), null); 
     } 

     void GotWeather(IAsyncResult result) 
     { 
      //Console.WriteLine("Get Weather Result: " + result.???); 
     } 

    } 
} 

答:

感谢TLiebe,你EndGetWeather建议我能得到像这样的工作:

using System.Windows; 
using TestConsume2343.ServiceReference1; 
using System; 

namespace TestConsume2343 
{ 
    public partial class Window1 : Window 
    { 
     GlobalWeatherSoapClient client = new GlobalWeatherSoapClient(); 

     public Window1() 
     { 
      InitializeComponent(); 
      client.BeginGetWeather("Berlin", "Germany", new AsyncCallback(GotWeather), null); 
     } 

     void GotWeather(IAsyncResult result) 
     { 
      Console.WriteLine("Get Weather Result: " + client.EndGetWeather(result).ToString()); 
     } 

    } 
} 
+0

什么是错误搞乱?没有打印?那么它不会如果代码被注释掉。 – leppie 2009-11-03 14:31:04

+0

以及如果我只是输出“结果”,它打印:获取天气结果:System.ServiceModel.Channels.ServiceChannel + SendAsyncResult,我不知道数据在“结果”对象中的位置,我想访问数据为我在这个例子中使用“e.Result”:http://tanguay.info/web/index.php?pg=codeExamples&id=205 – 2009-11-03 14:35:02

+0

什么.net版本? – 2009-11-03 14:37:33

回答

1

在你GotWeather()方法,你需要调用EndGetWeather()方法。看看MSDN的一些示例代码。您需要使用IAsyncResult对象来获取委托方法,以便您可以调用EndGetWeather()方法。

7

,我建议使用自动生成的代理提供的事件,而不是用的AsyncCallback

public void DoWork() 
{ 
    GlobalWeatherSoapClient client = new GlobalWeatherSoapClient(); 
    client.GetWeatherCompleted += new EventHandler<WeatherCompletedEventArgs>(client_GetWeatherCompleted); 
    client.GetWeatherAsync("Berlin", "Germany"); 
} 

void client_GetWeatherCompleted(object sender, WeatherCompletedEventArgs e) 
{ 
    Console.WriteLine("Get Weather Result: " + e.Result); 
}