我做了一个 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# - 使用 1.events/2 使用 Web 服务的优缺点是什么。同步结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1672739/