代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

使用1消费Web服务的优缺点是什么?事件/ 2。IAsyncResult?

  •  2
  • Edward Tanguay  · 技术社区  · 15 年前

    我做了一个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;
    }
    

    并与 开始/结束方法和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;
    
    }
    

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

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

    2 回复  |  直到 15 年前
        1
  •  2
  •   Konamiman    15 年前

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

        2
  •  0
  •   Vitaliy Liptchinsky    15 年前

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