在WP7上使用HttpWebRequest的ManualResetEvent

时间:2012-07-16 16:11:13

标签: windows-phone-7 httpwebrequest manualresetevent

首先,这可能被标记为以下线程的副本: Wait for HttpWebRequest.BeginGetResponse to finish in Windows Phone 7但是,该主题中的回复并没有帮助我克服我的问题。

首先,我在UI线程上收集用户数据以处理应用程序注册,其中我还有一个ManualResetEvent实例:

private static ManualResetEvent registrationEvent = new ManualResetEvent(false);

我有另一个处理注册过程的线程(包括HttpWebRequest.BeginGetResponse()及其相应的回调方法。)

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

在此调用之后,我通过调用

来阻止当前(UI)线程
registrationEvent.WaitOne();

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

一旦处理注册过程的线程开始,我就会实例化HttpWebRequest并在其上调用BeginGetResponse()方法。

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

现在问题是从不调用回调方法(下面的代码),应用程序只是冻结。似乎也没有抛出任何异常。

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

理想情况下,我希望我的应用程序在回调方法完成执行后从httpSessionCompleted()继续。有人可以帮我提一些指导/建议吗?

很抱歉这很详细。谢谢!

1 个答案:

答案 0 :(得分:0)

您不应阻止UI thread,而是使用回调模式。看看这个:Windows Phone 7 - wait for Webclient to complete。希望这有帮助