2012-02-22 150 views
0

這是我現在的功能,顯然不起作用。它不起作用的原因是因爲WebClient是異步的,並且data在被WebClient填充並在XML閱讀器上崩潰之前爲空。我該如何在此函數中調用WebClient,並且仍然允許它根據需要返回ServerResult,無論是否需要外部事件處理程序?如何調用一個需要調用WebClient的返回值的函數?

static public ServerResult isBarcodeCorrectOnServer(string barcode) 
{ 
      Dictionary<string, IPropertyListItem> dict = configDictionary(); 

      string urlString = (string.Format("http://www.myurl.com/app/getbarcodetype.php?realbarcode={0}&type={1}", barcode, dict["type"])); 

      WebClient wc = new WebClient(); 
      string data = ""; 
      wc.DownloadStringCompleted += (sender, e) => 
      { 
       if (e.Error == null) 
       { 
        //Process the result... 
        data = e.Result; 
       } 
      }; 
      wc.DownloadStringAsync(new Uri(urlString)); 

      StringReader stream = new StringReader(data); 
      var reader = XmlReader.Create(stream); 
      var document = XDocument.Load(reader); 
      var username = document.Descendants("item"); 
      var theDict = username.Elements().ToDictionary(ev => ev.Name.LocalName, ev => ev.Value); 

      if (theDict.ContainsKey("type") == true && theDict["type"].ToString() == dict["type"].ToString()) 
      { 
       return ServerResult.kOnServer; 
      } 
      else if (theDict.ContainsKey("type") == true) 
      { 
       return ServerResult.kWrongType; 
      } 
      else 
      { 
       return ServerResult.kNotOnServer; 
      } 
     } 
+0

爲什麼不使用非異步版本的DownloadString? – MarcinJuraszek 2012-02-22 22:11:47

+3

Silverlight不支持非異步 – BrokenGlass 2012-02-22 22:13:13

回答

5

你不能沒有「黑客」,你不應該 - 擁抱異步並傳入你想一旦下載完成後要執行的委託:

static public void isBarcodeCorrectOnServer(string barcode, Action<string> completed) 
{ 
    //.. 
    wc.DownloadStringCompleted += (sender, e) => 
    { 
     if (e.Error == null) 
     { 
      //Process the result... 
      data = e.Result; 
      completed(data); 
     } 
    }; 
    //.. 
} 

可以移動現在將所有處理代碼轉換爲您用下載結果調用的單獨方法。

+0

傳遞委託是我需要知道的。謝謝! – 2012-02-22 22:47:14

0

基本上,你不能。或者至少你不應該。你有一個方法,它被設計爲同步,在一個平臺上,它被設計爲異步 IO。

從根本上說,您應該設計自己的代碼以使用該平臺。接受它爲異步,並使調用代碼處理。

請注意,當C#5出現並且Windows Phone支持時,所有這些將是lot使用async更簡單。您將返回方法中的Task<ServerResult>,並返回WebClient的結果await。如果你只是爲了娛樂而開發(所以不要介意使用CTP,它有一些缺陷,並且可能無法用於市場應用),你可以使用do that today

相關問題