繁体   English   中英

从在单独线程中运行的函数返回值

[英]return value from a function running in separate thread

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

这是代码:

/**
 * 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”会更新返回的值吗?

提前完成了...

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

通过在同步语言之上添加注释,您将无法获得干净的异步。 理想情况下,异步操作应返回类似Future<T>以便“稍后会出现结果” - 以及查找结果的方式,是否已计算,是否存在这是一个例外等。这就是为什么在C#5中添加async/await原因 - 因为你不能在库级透明地执行它,即使使用AOP也是如此。 编写异步代码应该是一个非常慎重的决定 - 而不仅仅是通过注释固定到同步代码上的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM