简体   繁体   English

WP7应用程序永远不会退出BeginGetResponse并进入回调函数

[英]WP7 app never exits BeginGetResponse and goes into the callback function

I have the following code: 我有以下代码:

private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

            // End the operation
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            //Console.WriteLine("Please enter the input data to be posted:");
            //string postData = Console.ReadLine();
            string postData = "my data";

            // Convert the string into a byte array.
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Write to the request stream.
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();

                // Start the asynchronous operation to get the response
                IAsyncResult result =
                      (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);

        }

        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

            // End the operation
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();
            Console.WriteLine(responseString);
            // Close the stream object
            streamResponse.Close();
            streamRead.Close();

            // Release the HttpWebResponse
            response.Close();
            allDone.Set();

            Dispatcher.BeginInvoke((Action)(() => Debug.WriteLine("George")));
        }

However when my code hits BeginGetResponse it never exits (and I do not hit a breakpoint in the GetResponseCallback function). 但是,当我的代码命中BeginGetResponse时,它永远不会退出(我在GetResponseCallback函数中没有遇到断点)。 I tried adding the BeginInvoke call, but I still never enter this method. 我尝试添加BeginInvoke调用,但我仍然没有输入此方法。 This code works in a windows console app - it's on Windows Phone 7 that it doesn'teorg 此代码适用于Windows控制台应用程序 - 它位于Windows Phone 7上,它不具备此功能

Can anyone see what I am doing wrong? 谁能看到我做错了什么?

Thanks. 谢谢。

If you have created the HttpWebRequest on the UI thread, then make sure you don't block the UI thread, otherwise you can deadlock. 如果您已在UI线程上创建了HttpWebRequest,那么请确保您不阻止UI线程,否则您可能会死锁。

The sample from the desktop .NET you have linked isn't optimized for the current phone networking stack. 来自您链接的桌面.NET的示例未针对当前的电话网络堆栈进行优化。 You should change the code so that you create the HttpWebRequest on a background thread. 您应该更改代码,以便在后台线程上创建HttpWebRequest。

I can't see what's wrong with your code (maybe a complete example of what you're trying to do may help) but here's a simple working example of a way of performing the action you want to do. 我看不出你的代码有什么问题(也许你正在尝试做的事情的一个完整的例子可能会有所帮助),但这是一个简单的工作示例,说明了一种执行你想要做的动作的方法。
It posts some data to a URI and then passes the repsonse to a callback function: 它将一些数据发布到URI,然后将repsonse传递给回调函数:

Simply execute like this (use of a BackgroundWorker is not necessary but is recommended) 只需像这样执行(不需要使用BackgroundWorker但建议使用)

var bw = new BackgroundWorker();
bw.DoWork += (o, args) => PostDataToWebService("http://example.com/something", "key=value&key2=value2", MyCallback);
bw.RunWorkerAsync();

Here's the callback function it refers to: 这是它引用的回调函数:
(You can change this however is appropriate to your needs.) (您可以根据需要更改此选项。)

public static void MyCallback(string aString, Exception e)
{
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        if (e == null)
        {
            // aString is the response from the web server
            MessageBox.Show(aString, "success", MessageBoxButton.OK);
        }
        else
        {
            MessageBox.Show(e.Message, "error", MessageBoxButton.OK);
        }
    });
}

Here's the actual method: 这是实际的方法:

public void PostDataToWebService(string url, string data, Action<string, Exception> callback)
{
    if (callback == null)
    {
        throw new Exception("callback may not be null");
    }

    try
    {
        var uri = new Uri(url, UriKind.Absolute);
        var req = HttpWebRequest.CreateHttp(uri);

        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";

        AsyncCallback GetTheResponse = ar =>
            {
                try
                {
                    var result = ar.GetResponseAsString();

                    callback(result, null);
                }
                catch (Exception ex)
                {
                    callback(null, ex);
                }
            };

        AsyncCallback SetTheBodyOfTheRequest = ar =>
            {
                var request = ar.SetRequestBody(data);

                request.BeginGetResponse(GetTheResponse, request);
            };

        req.BeginGetRequestStream(SetTheBodyOfTheRequest, req);
    }
    catch (Exception ex)
    {
        callback(null, ex);
    }
}

and here are the extension/helper methods it uses: 以下是它使用的扩展/辅助方法:

public static class IAsyncResultExtensions
{
    public static string GetResponseAsString(this IAsyncResult asyncResult)
    {
        string responseString;

        var request = (HttpWebRequest)asyncResult.AsyncState;

        using (var resp = (HttpWebResponse)request.EndGetResponse(asyncResult))
        {
            using (var streamResponse = resp.GetResponseStream())
            {
                using (var streamRead = new StreamReader(streamResponse))
                {
                    responseString = streamRead.ReadToEnd();
                }
            }
        }

        return responseString;
    }

    public static HttpWebRequest SetRequestBody(this IAsyncResult asyncResult, string body)
    {
        var request = (HttpWebRequest)asyncResult.AsyncState;

        using (var postStream = request.EndGetRequestStream(asyncResult))
        {
            using (var memStream = new MemoryStream())
            {
                var content = body;

                var bytes = System.Text.Encoding.UTF8.GetBytes(content);

                memStream.Write(bytes, 0, bytes.Length);

                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);

                postStream.Write(tempBuffer, 0, tempBuffer.Length);
            }
        }

        return request;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM