首先,这可能被标记为以下线程的副本: 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() 继续。有人可以帮我一些指导/建议吗?
很抱歉很冗长。谢谢!