【发布时间】: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