精彩的人生

          好好工作,好好生活

          BlogJava 首頁(yè) 新隨筆 聯(lián)系 聚合 管理
            147 Posts :: 0 Stories :: 250 Comments :: 0 Trackbacks
          為舉例說(shuō)明異步 Web 方法,我從一個(gè)名為 LengthyProcedure 的簡(jiǎn)單同步 Web 方法開(kāi)始,其代碼如下所示。然后我們?cè)倏匆豢慈绾萎惒酵瓿上嗤娜蝿?wù)。LengthyProcedure 只占用給定的毫秒數(shù)。

          [WebService]

          public class SyncWebService : System.Web.Services.WebService
          {

          [WebMethod]
          public string LengthyProcedure(int milliseconds)
          {
          System.Threading.Thread.Sleep(milliseconds);
          return "成功";
          }
          }

          現(xiàn)在我們將 LengthyProcedure 轉(zhuǎn)換為異步 Web 方法。我們必須創(chuàng)建如前所述的 BeginLengthyProcedure 函數(shù)和 EndLengthyProcedure 函數(shù)。請(qǐng)記住,我們的 BeginLengthyProcedure 調(diào)用需要返回一個(gè) IAsyncResult 接口。這里,我打算使用一個(gè)委托以及該委托上的 BeginInvoke 方法,讓我們的 BeginLengthyProcedure 調(diào)用進(jìn)行異步方法調(diào)用。傳遞到 BeginLengthyProcedure 的回調(diào)函數(shù)將被傳遞到委托上的 BeginInvoke 方法,從 BeginInvoke 返回的 IAsyncResult 將被 BeginLengthyProcedure 方法返回。

          當(dāng)委托完成時(shí),將調(diào)用 EndLengthyProcedure 方法。我們將調(diào)用委托上的 EndInvoke 方法,以傳入 IAsyncResult,并將其作為 EndLengthyProcedure 調(diào)用的輸入。返回的字符串將是從該 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 閱讀(305) 評(píng)論(0)  編輯  收藏 所屬分類(lèi): Web Service
          主站蜘蛛池模板: 旬邑县| 横山县| 海南省| 论坛| 新兴县| 酉阳| 桃园县| 滦南县| 肃宁县| 哈密市| 嘉鱼县| 海原县| 英山县| 利辛县| 彰化市| 滕州市| 海林市| 镇原县| 广丰县| 普兰县| 广饶县| 洛南县| 昔阳县| 汝阳县| 花莲县| 罗源县| 仁怀市| 仁布县| 霍州市| 滨海县| 吉安县| 武隆县| 临沧市| 鄯善县| 沾益县| 海原县| 白玉县| 漳州市| 康平县| 大理市| 四川省|