簡體   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