如何异步调用此Web服务?

Edw*_*uay 4 c# asynchronous web-services

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

    }
}
Run Code Online (Sandbox Code Playgroud)

回答:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Pie*_*ant 9

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


TLi*_*ebe 1

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