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



这是我现在拥有的函数,它显然不起作用。它不起作用的原因是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;
            }
        }

你不能没有"hacks",也不应该接受异步并传递一个你想在下载完成后执行的委托:

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);
       }
    };
    //..
}

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

基本上你做不到。或者至少你不应该。你有一个设计为同步的方法,在一个设计用于异步IO的平台上。

从根本上讲,您应该设计您的代码来使用该平台。接受它是异步的,并让调用代码处理这个问题。

请注意,当C#5问世并得到Windows Phone的支持时,使用async,所有这些都将变得更加简单。您将从该方法返回一个Task<ServerResult>awaitWebClient的结果。如果你只是为了好玩而开发(所以不要介意使用有一些错误的CTP,它可能无法用于市场应用程序),你今天就可以这么做了。

最新更新