频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

服务器端异步Web方法(二)

来源: 作者: 出处:巧巧读书 2006-04-28 进入讨论组
谢 谢 收 藏 http://www.qqread.com/network/server/b266393.html
  简单的异步 Web 方法
  为举例说明异步 Web 方法,我从一个名为 LengthyProcedure 的简单同步 Web 方法开始,其代码如下所示。然后我们再看一看如何异步完成相同的任务。LengthyProcedure 只占用给定的毫秒数。
  
  [WebService]
  
  public class SyncWebService : System.Web.Services.WebService
  
  {
  
    [WebMethod]
  
    public string LengthyProcedure(int milliseconds)
  
    {
  
      System.Threading.Thread.Sleep(milliseconds);
  
      return "成功";
  
    }
  
  }
  
  现在我们将 LengthyProcedure 转换为异步 Web 方法。我们必须创建如前所述的 BeginLengthyProcedure 函数和 EndLengthyProcedure 函数。请记住,我们的 BeginLengthyProcedure 调用需要返回一个 IAsyncResult 接口。这里,我打算使用一个委托以及该委托上的 BeginInvoke 方法,让我们的 BeginLengthyProcedure 调用进行异步方法调用。传递到 BeginLengthyProcedure 的回调函数将被传递到委托上的 BeginInvoke 方法,从 BeginInvoke 返回的 IAsyncResult 将被 BeginLengthyProcedure 方法返回。
  
  当委托完成时,将调用 EndLengthyProcedure 方法。我们将调用委托上的 EndInvoke 方法,以传入 IAsyncResult,并将其作为 EndLengthyProcedure 调用的输入。返回的字符串将是从该 Web 方法返回的字符串。下面是其代码:
  
  [WebService]
  
  public class AsyncWebService : System.Web.Services.WebService
  
  {
  
    public delegate string LengthyProcedureAsyncStub(
  
      int milliseconds);
  
    public string LengthyProcedure(int milliseconds)
  
    {
  
      System.Threading.Thread.Sleep(milliseconds);
  
      return "成功";
  
    }
  
    public class MyState
  
    {
  
      public object previousState;
  
      public LengthyProcedureAsyncStub asyncStub;
  
    }
  
    [ System.Web.Services.WebMethod ]
  
    public IAsyncResult BeginLengthyProcedure(int milliseconds,
  
      AsyncCallback cb, object s)
  
    {
  
      LengthyProcedureAsyncStub stub
  
        = new LengthyProcedureAsyncStub(LengthyProcedure);
  
      MyState ms = new MyState();
  
      ms.previousState = s;
  
      ms.asyncStub = stub;
  
      return stub.BeginInvoke(milliseconds, cb, ms);
  
    }
  
    [ System.Web.Services.WebMethod ]
  
    public string EndLengthyProcedure(IAsyncResult call)
  
    {
  
      MyState ms = (MyState)call.AsyncState;
  
      return ms.asyncStub.EndInvoke(call);
  
    }
  
  } 更多文章 更多内容请看FTP服务器双核服务器技术网站服务器的选型专题,或进入讨论组讨论。
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章