【问题标题】:What are pros and cons of consuming web services with 1. events / 2. IAsyncResult?使用 1. 事件 / 2. IAsyncResult 使用 Web 服务的优缺点是什么?
【发布时间】:2009-11-04 09:55:56
【问题描述】:

我制作了一个 WPF 示例,它以两种不同的方式使用 Web 服务 (www.webservicex.com/globalweather.asmx):

有这样的事件

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

使用 Begin/End 方法和 IAsyncResult 如下:

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;

}

这两种方法似乎执行完全相同的任务。

它们的优缺点是什么?你什么时候会使用一个而不是另一个?

【问题讨论】:

    标签: c# web-services events iasyncresult


    【解决方案1】:

    对于远程服务,我通常更喜欢使用回调而不是事件处理程序,因为它会导致代码更具可读性/可维护性(通过查看服务调用调用代码,我知道调用完成时将执行哪些代码)。此外,在使用事件处理程序时,您需要注意不要多次声明它们。

    【讨论】:

      【解决方案2】:

      这只是口味问题。与技术预期没有区别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-01
        • 2016-04-26
        • 2011-07-20
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 2010-09-06
        • 2015-01-30
        相关资源
        最近更新 更多