I made a WPF example that consumes a web service (www.webservicex.com/globalweather.asmx) in two different ways:
with events like this:
public Window1()
{
InitializeComponent();
DataContext = this;
Location = "loading...";
Temperature = "loading...";
RelativeHumidity = "loading...";
client.GetWeatherCompleted +=
new EventHandler<GetWeatherCompletedEventArgs>(client_GetWeatherCompleted);
client.GetWeatherAsync("Berlin", "Germany");
}
void client_GetWeatherCompleted(object sender, GetWeatherCompletedEventArgs e)
{
XDocument xdoc = XDocument.Parse(e.Result);
Location = xdoc.Descendants("Location").Single().Value;
Temperature = xdoc.Descendants("Temperature").Single().Value;
RelativeHumidity = xdoc.Descendants("RelativeHumidity").Single().Value;
}
and with the Begin/End methods and IAsyncResult like this:
public Window1()
{
InitializeComponent();
DataContext = this;
Location = "loading...";
Temperature = "loading...";
RelativeHumidity = "loading...";
client.BeginGetWeather("Berlin", "Germany", new AsyncCallback(GotWeather), null);
}
void GotWeather(IAsyncResult result)
{
string xml = client.EndGetWeather(result).ToString();
XDocument xdoc = XDocument.Parse(xml);
Location = xdoc.Descendants("Location").Single().Value;
Temperature = xdoc.Descendants("Temperature").Single().Value;
RelativeHumidity = xdoc.Descendants("RelativeHumidity").Single().Value;
}
These two approaches seem to perform the exact same task.
What are their advantages and disadvantages? When would you use one and not the other?