开发者

How can I call this webservice asynchronously?

In Visual Studio I created a web service (and checked "generate asynchronous operations") on this URL:

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

and can get the data out synchronously but what is the syntax for getting the data out asychronously?

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("Ge开发者_如何学Got Weather Result: " + getWeatherResult); //works

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

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

    }
}

Answer:

Thanks TLiebe, with your EndGetWeather suggestion I was able to get it to work like this:

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

    }
}


I suggest using the event provided by the auto-generated proxy instead of messing with the 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);
}


In your GotWeather() method you need to call the EndGetWeather() method. Have a look at some of the sample code at MSDN. You need to use the IAsyncResult object to get your delegate method so that you can call the EndGetWeather() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜