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?
For the case of remote services, I usually prefer to use callbacks instead of event handlers since it leads to more readable/maintainable code (by just looking at the service call invokation code I know which code will be executed when the call finishes). Moreover when using event handlers you need to have care for not declaring them more than once.