开发者

HttpWebRequest.EndGetResponse() returns null on Windows Phone 7.1?

I don't quite understand why EndGetResponse() returns null in the following code:

    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
        var request = WebRequest.Create("http://www.microsoft.com");
        using (var response = request.EndGetResponse(request.BeginGetResponse(ar => { }, null)))
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            string content = reader.ReadToEnd();
        }
开发者_JS百科    }

(to reproduce, replace the empty Application_Launching handler in a newly created Windows Phone Application with the code above)

Is this a bug in the framework?


Apparently I've committed a typical noob mistake, I dared to block the main/UI thread. It seems Silverlight wants to avoid that at all costs and refuses my request by immediately returning null. Ok, but wouldn't it be nice to throw an appropriate exception instead of returning a value that the documentation doesn't even mention as a possibility?

Anyway, here's the corrected code:

    private void Application_Launching(object sender, LaunchingEventArgs e)
    {
        var request = WebRequest.Create("http://www.microsoft.com");
        var asyncResult = request.BeginGetResponse(
            ar =>
            {
                using (var response = request.EndGetResponse(ar))
                using (var responseStream = response.GetResponseStream())
                using (var reader = new StreamReader(responseStream))
                {
                    string content = reader.ReadToEnd();
                }
            }, null);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜