首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

异步模式调用同步方法

2012-06-28 
异步方式调用同步方法系统中同步方法很多,当串行时响应时间会比较长,有些调用可以异步来做,当需要结果时只

异步方式调用同步方法

系统中同步方法很多,当串行时响应时间会比较长,有些调用可以异步来做,当需要结果时只要有就行。如果调用的方法本身就是异步的这个还好。但是因为很多方法都是同步实现的,所以急需要一种框架或者工具来实现同步方法的异步调用,我搜索了下没找到比较好的解决方案,不过也有一些可供参考的,这里总结下:

?

?

1:NET Framework提供的异步调用同步方法

?

使用异步方式调用同步方法

http://msdn.microsoft.com/zh-cn/library/2e08f6yc(v=vs.80).aspx

?

截取API使用方式如下:

?

?

// Create the delegate.AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);       // Initiate the asychronous call.IAsyncResult result = caller.BeginInvoke(3000,                 out threadId, null, null);string returnValue = caller.EndInvoke(out threadId, result);
?

ad.TestMethod ?就是需要异步调用的同步方法,可惜java没有这么简洁优美的语法。

?

2:目前找到的实现异步调用的java框架 ?asyn4j

http://code.google.com/p/asyn4j/

?

国人原创的,api还可以,还不支持future模式,但是支持也很简单。

?

?

3:spring 3.0提供的任务调度

?

http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html

?

API使用例子:

?

simplest case, the annotation may be applied to a void-returning method.@Asyncvoid doSomething() {    // this will be executed asynchronously}
Unlike the methods annotated with the @Scheduled annotation, these methods can expect arguments, because they will be invoked in the "normal" way by callers at runtime rather than from a scheduled task being managed by the container. For example, the following is a legitimate application of the @Async annotation.@Asyncvoid doSomething(String s) {    // this will be executed asynchronously}
Even methods that return a value can be invoked asynchronously. However, such methods are required to have a Future typed return value. This still provides the benefit of asynchronous execution so that the caller can perform other tasks prior to calling get() on that Future.@AsyncFuture<String> returnSomething(int i) {    // this will be executed asynchronously}
?

?

热点排行