精彩的人生

          好好工作,好好生活

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            147 Posts :: 0 Stories :: 250 Comments :: 0 Trackbacks
          為舉例說明異步 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);
          }
          }


          原文地址:http://ewebapp.cnblogs.com/articles/237375.html
          posted on 2006-05-07 15:18 hopeshared 閱讀(310) 評論(0)  編輯  收藏 所屬分類: Web Service
          主站蜘蛛池模板: 莱阳市| 崇仁县| 中江县| 阿拉善右旗| 綦江县| 宜春市| 永川市| 克什克腾旗| 六安市| 新野县| 五峰| 平遥县| 台州市| 彭州市| 丹巴县| 香格里拉县| 呼图壁县| 八宿县| 海南省| 南岸区| 遂宁市| 平阴县| 莆田市| 行唐县| 海丰县| 孙吴县| 台中县| 赤壁市| 惠来县| 榆树市| 黄大仙区| 久治县| 盐边县| 阿鲁科尔沁旗| 怀仁县| 绥中县| 濮阳市| 曲靖市| 同仁县| 祁连县| 深泽县|