ManualResetEvent with HttpWebRequest on WP7

夙愿已清 提交于 2019-12-11 11:18:42

问题


To start off with, this might be tagged as a duplicate of the following thread: Wait for HttpWebRequest.BeginGetResponse to finish in Windows Phone 7, however, the responses in that thread did not help me get over my problem.

To begin with, I am collecting user data on the UI Thread in order to process application registration, where I also have an instance of ManualResetEvent:

private static ManualResetEvent registrationEvent = new ManualResetEvent(false);

I have another thread which handles the registration process (and includes the HttpWebRequest.BeginGetResponse() and its corresponding callback method.)

Thread t = new Thread(() => RegistrationHandler.sendRegistrationData(url));
t.Start();

Right after this call, I block the current (UI) thread with a call to

registrationEvent.WaitOne();

//Process the response, update some UI elements and navigate to a different page.
httpSessionCompleted(response);

Once the thread handling the registration process starts, I am instantiating HttpWebRequest and invoking the BeginGetResponse() method on it.

try
{
    HttpWebRequest request = HttpWebRequest.CreateHttp(url);
    request.Method = "POST";
    request.ContentType = mimeType;

    request.BeginGetResponse(new AsyncCallback(GetRequestCallback), request);
}
catch (Exception ex)
{
    Console.WriteLine("Exception caught in sendData(): {0}", ex.Message);
}

Now the issue is that the callback method (code below) is never invoked, and the application just freezes. There also doesn't seem to be any exception(s) thrown either.

try
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

    if (request != null)
    {
        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult))
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        String result = reader.ReadToEnd();
                        Globals.HostResponse = result;
                        //Signalling the calling thread to continue execution
                        RegistrationPage.RegistrationEvent.Set();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in GetRequestCallback(): {0}", ex.Message);
        }

I ideally want my application to continue from httpSessionCompleted() after the callback method finishes execution. Can someone please help me with some guidance/suggestions?

Sorry for being verbose. Thanks!


回答1:


You should not block UI thread, use callback pattern instead. Look at this: Windows Phone 7 - wait for Webclient to complete . Hope this helps



来源:https://stackoverflow.com/questions/11508258/manualresetevent-with-httpwebrequest-on-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!