2011-02-24 31 views
1

我有一个Silverlight项目,它通过它的服务引用:DataService(在ASP.NET项目中完成的服务)接受一些加密字符串。Silverlight中有趣的服务行为

从TransactionServices.cs的方法来获得加密的字符串是:

public void GetEncryptedString(string original) 
    { 
     DataService.DataServiceClient dataSvc = WebServiceHelper.Create(); 
     dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted); 
     dataSvc.GetEncryptedStringAsync(original); 
    } 

在完成,放于encodedString VAR的结果(这是一个空值初始化):

void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     { 
      try 
      { 
       if (e.Result == null) return; 
       this.encodedString = e.Result; 
      } 
      catch (Exception ex) 
      { 
       Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}", 
        ex.Message, ex.StackTrace); 
       MessageBox.Show(ex.ToString()); 
      } 
     } 
    } 

现在我想从我的MainPage.xaml得到编码的字符串,例如:

TransactionService ts = new TransactionService(); 
        ts.GetEncryptedString(url); 
        Console.WriteLine(ts.encodedString); 

我不理解为什么ts.encodedString是空的。当我进行调试时,我发现它实际上打印出空白,并且AFTER将它传递给void dataSvc_GetEncryptedStringCompleted来获取结果并填充它。

你能指出我做错了什么吗?有没有办法等待encodedString被提取,并且只有在这之后继续?

非常感谢。

回答

0

当您拨打ts.GetEncryptedString(url);时,您刚刚开始异步操作。因此,您正在访问的值将仅在回调方法中设置。

但您在回调修改值之前访问它。

里面我是用意志的解决方案看起来类似如下因素:

重新定义GetEncryptedString方法签名。

public void GetEncryptedString(string original, Action callback) 
    { 
     DataService.DataServiceClient dataSvc = WebServiceHelper.Create(); 
     dataSvc.GetEncryptedStringCompleted += (o,e) => 
{ 
dataSvc_GetEncryptedStringCompleted(o,e); 
callback(); 
}    
     dataSvc.GetEncryptedStringAsync(original); 
    } 

这样称呼它:

ts.GetEncryptedString(URL,OtherLogicDependantOnResult);

其中

OtherLogicDependantOnResult是

void OtherLogicDependantOnResult() 
{ 
//... Code 
} 
+0

,是有什么办法让它同步?我想重定向到它加密的url,所以我怎么才能等待回调加载的值? –

+0

我正在寻找解决方案一段时间,但后来我只是习惯了。无论如何,你可以使这个调用同步。看看http://blog.benday.com/archive/2010/05/15/23277.aspx – v00d00

+0

非常感谢。似乎使用lambda表达式是关键! –