2009-11-03 44 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); 
}