在AsyncCallback中返回语句?

时间:2015-05-08 18:05:17

标签: c# windows-phone-7

我正在编写一个Windows Phone 7应用程序,其中一部分接收一个URL并检查该网站是否仍然有效。问题是我无法在HTTP请求中执行返回语句,因此,不起作用的网站将不会显示为不在应用程序中工作。

        private string check(string url)
    {
        try
        {
            var request = (HttpWebRequest)WebRequest.Create(
            new Uri(url));
            request.BeginGetResponse(r =>
            {
                try
                {
                    var httpRequest = (HttpWebRequest)r.AsyncState;
                    var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

                    using (var reader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var response = reader.ReadToEnd();
                    }
                }
                catch
                {
                    return "\u2612"; //Error here
                }
            }, request);
        }
        catch
        {
            return "\u2612";
        }
        return "\u2611";
    }

当我尝试编译此代码时,我收到了以下错误:

  

错误1由于'System.AsyncCallback'返回void,因此返回关键字后面不能包含对象表达式

     

错误2无法将lambda表达式转换为委托类型'System.AsyncCallback',因为块中的某些返回类型不能隐式转换为委托返回类型

有没有办法绕过这个或其他方式让return语句工作?

1 个答案:

答案 0 :(得分:1)

你可以使用这样的回调结果类型:

  private void check(string url, Action<string> act)
  {
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(
        new Uri(url));
        request.BeginGetResponse(r =>
        {
            try
            {
                var httpRequest = (HttpWebRequest)r.AsyncState;
                var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

                using (var reader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var response = reader.ReadToEnd();
                }
            }
            catch
            {
                act("\u2612");
            }
        }, request);
    }
    catch
    {
        act(\u2612");
    }
    act("\u2611");  //may be this call must comment!
}

在匿名方法中,如果返回值,则意味着匿名方法将返回值,而不是谁调用它的方法。

如果你写

request.BeginGetResponse(r => {
    return "";
}

这意味着你将匿名方法传递给没有输入参数和返回字符串参数的BeginGetResponse方法。

和BeginGetResponse dos不接受这种方法

<强>更新

当你想要使用时:

check(s, (myReturnValue) => {
     //myReturnValue is result of method
     results.Add(myReturnValue);
     //Code in here guaranteed results is filled always...
});
//Code in here is not guaranteed  results is filled if you comment code that i suggested, because it fill in callback method and callback method will called in async method...

重要

此方法将执行异步操作 results.Add(myReturnValue);是在调用check方法后完全执行,因为它是异步的 这样你就不能显式地有返回值了,你可以使用回调方法。

如果你想在没有异步的情况下执行并明确定义check方法的返回值,你可以调用GetResponse而不是BeginGetResponse。