views:

173

answers:

2

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

    }
}
+1  A: 

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.

TLiebe
+1  A: 

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);
}
Pierre-Alain Vigeant