开发者

What are pros and cons of consuming web services with 1. events / 2. IAsyncResult?

开发者 https://www.devze.com 2022-12-10 16:45 出处:网络
I made a WPF example that consumes a web service (www.webservicex.com/globalweather.asmx) in two different ways:

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_Ge开发者_如何学CtWeatherCompleted(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.


That's just matter of taste. No difference from technical prospective.

0

精彩评论

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