0

如果它们上存在“异步”注释,我有这段代码允许在单独的线程中执行函数。一切正常,除了我意识到我还必须处理我刚刚添加的一些新函数的返回值的那一天。我可以为此使用处理程序和消息传递,但是,由于已经构建了项目结构(它很大并且工作正常),我无法更改现有函数来处理消息传递。

这是代码:

/**
 * Defining the Asynch interface
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Asynch {}

/**
 * Implementation of the Asynch interface. Every method in our controllers
 * goes through this interceptor. If the Asynch annotation is present,
 * this implementation invokes a new Thread to execute the method. Simple!
 */
public class AsynchInterceptor implements MethodInterceptor {
  public Object invoke(final MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    Annotation[] declaredAnnotations = method.getDeclaredAnnotations(); 
    if(declaredAnnotations != null && declaredAnnotations.length > 0) {
      for (Annotation annotation : declaredAnnotations) {
        if(annotation instanceof Asynch) {
          //start the requested task in a new thread and immediately
          //return back control to the caller
          new Thread(invocation.getMethod().getName()) {
            public void execute() {
              invocation.proceed();
            }
          }.start();
          return null;
        }
      }
    }
    return invocation.proceed();
  }
}

现在,我该如何转换它,如果它是这样的:

@Asynch
public MyClass getFeedback(int clientId){

}

MyClass mResult = getFeedback(12345);

“mResult”会用返回的值更新吗?

提前谢谢...

4

1 回答 1

2

你不能,从根本上说。getFeedback必须以同步的方式返回一些东西——虽然在某些情况下你可以稍后更新返回的对象,但在其他情况下你显然不能——像不可变的类String就是明显的例子。以后不能更改变量 mResult的值……毕竟,它很可能是一个局部变量。事实上,在计算结果时,使用它的方法可能已经完成......使用虚假值。

仅仅通过在同步语言之上添加注释,您将无法获得干净的异步。理想情况下,异步操作应该返回类似 a 的内容Future<T>,表示“稍后会有结果”——以及找出结果是什么、是否已计算、是否有异常等的方法. 这种事情正是async/await在 C# 5 中添加的原因——因为您不能只在库级别透明地执行此操作,即使使用 AOP 也是如此。编写异步代码应该是一个非常深思熟虑的决定——不仅仅是通过注释固定在同步代码上的东西。

于 2013-02-11T08:06:56.943 回答