2011-02-24 38 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表達式是關鍵! –