2013-03-23 39 views
0

我在写一个简单的Silverlight应用程序和WCF服务。 我想创建一个返回值的同步方法。 该方法本身从WCF服务调用异步方法。在我调用异步方法之后,我想获取它的值,并返回给发件人。 我听说Rx可以解决这类问题。Silverlight:使用Rx从同步方法返回值

这是我的代码:

private void btnCreate_Click(object sender, RoutedEventArgs e) 
    { 
     string myResult = getMyBook(txtBookName.Text); 
     MessageBox.Show("Result\n" + myResult); 
     // myResult will be use for another purpose here.. 
    } 

    // I want this method can be called anywhere, as long as the caller still in the same namespace. 
    public string getMyBook(string bookName) 
    { 
     Servo.ServoClient svc = new ServoClient(); 
     string returnValue = ""; 

     var o = Observable.FromEventPattern<GetBookCompletedEventArgs>(svc, "GetBookCompleted"); 
     o.Subscribe(
      b => returnValue = b.EventArgs.Result 
      ); 

     svc.GetBookAsync(bookName); 
     return returnValue; 
    } 

当我点击的BtnCreate,myResult变量仍然是空的。我的代码有问题吗?或者,也许我只是不明白Rx概念?我是Rx的新手。

我的目标是:我需要的结果从异步方法(myResult变量),然后在后面的代码中使用。

回答

0

请记住,GetBookAsync立即返回,并将返回存储在returnvalue中的值。当数据到达时,返回值将超出范围,届时btnCreate将完成。

U可以在GetBookAsync上使用await,以便在继续之前等待数据到达。不要忘记,这意味着你也需要方法上的异步。

不是一个很好的例子或使用RX或等待,但尝试是我们如何学习!

1

这比关键词更适合于async/await关键字。 Rx主要用于管理数据流,而在这种情况下,您只需要同步管理异步呼叫。你可以尝试使用的Rx像这样:

public string getMyBook(string bookName) 
{ 
    Servo.ServoClient svc = new ServoClient(); 
    svc.GetBookAsync(bookName); 

    var o = Observable.FromEventPattern<GetBookCompletedEventArgs>(svc, "GetBookCompleted"); 
    return o.First().EventArgs.Result; 
} 

但是,如果GetBookAsync提高您订阅事件之前,该线程将永远阻塞。你可能会搞砸.Replay().Connect(),但你应该只使用async/await