首页 | 互联网 | IT动态 | IT培训 | Cisco | Windows | Linux | Java | .Net | Oracle | 软件测试 | C/C++ | 嵌入式开发 | 存储世界 | 服务器
网络设备 | IDC | 安全 | 求职招聘 | 数字网校 | 笔记本电脑 | 北大青鸟 | 技术专题 | 电子书下载 | 教学视频 | 源码下载 | 搜索 | 博客 | 论坛
中国IT实验室Dotnet频道
中国IT教育
Google
首页 ASP.NET  C#  XML/WebService ADO.NET VC.NET VB.NET .NET 资讯动态 专题 RSS订阅 讨论 下载
您现在的位置: 中国IT实验室 >> Dotnet >> ASP.NET >> 正文

ASP.NET2.0中数据源控件之异步数据访问

  示例 
   
  现在,新的 AsyncWeatherDataSource 将从 AsyncDataSourceControl 中派生,而AsyncWeatherDataSourceView 将从 AsyncDataSourceView 中派生。
  
  public class AsyncWeatherDataSource : AsyncDataSourceControl {
  
  //与 WeatherDataSource 相同
  }
  
  private sealed class AsyncWeatherDataSourceView : AsyncDataSourceView {
  private AsyncWeatherDataSource _owner;
  private WeatherService _weatherService;
  
  public AsyncWeatherDataSourceView(AsyncWeatherDataSource owner,
  string viewName)
  : base(owner, viewName) {
  _owner = owner;
  }
  
  protected override IAsyncResult BeginExecuteSelect(DataSourceSelectArguments arguments,
  AsyncCallback asyncCallback,
  object asyncState) {
  arguments.RaiseUnsupportedCapabilitiesError(this);
  
  string zipCode = _owner.GetSelectedZipCode();
  if (zipCode.Length == 0) {
  return new SynchronousAsyncSelectResult(/* selectResult */
  null,
  asyncCallback, asyncState);
  }
  
  _weatherService = new WeatherService(zipCode);
  return _weatherService.BeginGetWeather(asyncCallback, asyncState);
  }
  
  protected override IEnumerable EndExecuteSelect(IAsyncResult asyncResult) {
  SynchronousAsyncSelectResult syncResult =
  asyncResult as SynchronousAsyncSelectResult;
  if (syncResult != null) {
  return syncResult.SelectResult;
  }
  else {
  Weather weatherObject =
  _weatherService.EndGetWeather(asyncResult);
  _weatherService = null;
  
  if (weatherObject != null) {
  return new Weather[] { weatherObject };
  }
  }
  
  return null;
  }
  } 
   
  要注意的关键问题是,在使用该框架时,只需要实现 BeginExecuteSelect 和 EndExecuteSelect。在它们的实现过程中,通常要调用由该框架中的各种对象(例如 WebRequest 或 IO 流)所揭示的 BeginXXX 和 EndXXX 方法(在 Visual Studio 2005 中,还需要调用 SqlDataCommand),并返回 IAsyncResult。在此示例中,有一个封装了基础 WebRequest 对象的 WeatherService 帮助程序类。 
   
  对于那些实际缺少异步模式的框架,您在此会看到有效的异步模式;以及您要实现的 BeginExecuteSelect 和 EndExecuteSelect,和您要调用以返回 IAsyncResult 实例的 Begin 和 End 方法。 
   
  最有趣的可能是 SynchronousAsyncSelectResult 类(在某种程度上而言是一种矛盾)。此类是框架附带的。它基本上是一个 IAsyncResult 实现,可使数据立即可用,并从其 IAsyncResult.CompletedSynchronously 属性报告 true。到目前为止,这仅适用于未选择邮政编码的情况,并且需要返回 null(启动异步任务而只返回 null 是没有意义的),但正如您会在下文中看到的,这在其他方案中也是有用的。 
   
  页面基础结构隐藏了在 Microsoft ASP.net 上下文中执行异步工作的大部分详细信息。希望在此提供的框架使您执行最少的操作就能编写使用此基础结构的数据源。不过,就其本质而言,实现异步行为是复杂的。有时候,第一次阅读本文时会有一些疑问,而第二次阅读时可能就明白了。您可以使用下面“我的评论”表单来发送问题或进行讨论。

上一页  [1] [2] 

【责编:yuan】

中国IT教育

相关产品和培训
文章评论
 友情推荐链接
 认证培训
 专题推荐

 ·算法分析与设计之五大常用算法
 ·开发必备 漫谈Java加密保护
 ·嵌入式开发--ARM技术专题
 ·C/C++指针,认真了解,灵活运用
 ·.NET开发:C#实用基础教程
 ·软件测试工具QTP学习专题
 ·嵌入式开发单片机解决方案专题
 ·Java开发环境 Greenfoot 程序员手册
 ·C++对象布局及多态实现的探索
 ·常见排序算法的实现
 今日更新
 社区讨论
 博客论点
 频道精选
 Dotnet频道相关导航