這是我現在的功能,顯然不起作用。它不起作用的原因是因爲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;
}
}
爲什麼不使用非異步版本的DownloadString? – MarcinJuraszek 2012-02-22 22:11:47
Silverlight不支持非異步 – BrokenGlass 2012-02-22 22:13:13