如何调用需要调用WebClient的返回值的函数?

Eth*_*len 0 .net c# silverlight visual-studio windows-phone-7

这是我现在的功能,显然不起作用.它不起作用的原因是因为WebClient是异步的并且data在WebClient填充并且在XML阅读器上崩溃之前是空的.如何在此函数中调用WebClient并仍然允许它在ServerResult需要或不需要外部事件处理程序时根据需要返回?

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 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);
       }
    };
    //..
}
Run Code Online (Sandbox Code Playgroud)

您现在可以将所有处理代码移动到您使用下载结果调用的单独方法中.