如何异步调用此Web服务?

时间:2009-11-03 14:28:25

标签: c# web-services asynchronous

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

  

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()); 
        }

    }
}

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

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