代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何异步调用此Web服务?

  •  4
  • Edward Tanguay  · 技术社区  · 15 年前

    在Visual Studio中,我创建了一个 Web服务 (并选中“生成异步操作”)在此URL上:

    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.???); 
            }
    
        }
    }
    

    答:

    谢谢特利比,和你的 阴天天气 建议我能让它这样工作:

    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()); 
            }
    
        }
    }
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   TLiebe    15 年前

    在gotWeather()方法中,需要调用endGetWeather()方法。请看下面的一些示例代码 MSDN .您需要使用IAsyncResult对象获取委托方法,以便可以调用endGetWeather()方法。

        2
  •  8
  •   Pierre-Alain Vigeant    15 年前

    我建议使用自动生成的代理提供的事件,而不是处理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);
    }