新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:服务器端异步 Web 方法(二)

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

新客网 XKER.COM 2004-06-16 来源: 收藏本文
简单的异步 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);

}

}
收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐