我制作了一个 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;
}
这两种方法似乎执行完全相同的任务。
它们的优点和缺点是什么?你什么时候用一个而不用另一个?