2012-07-16 66 views
1

要开始使用,可能会将其标记为以下线程的副本: Wait for HttpWebRequest.BeginGetResponse to finish in Windows Phone 7,但是该线程中的响应并未帮助我解决我的问题。ManualResetEvent with WP7上的HttpWebRequest

首先,我收集关于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); 
} 

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

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()继续。有人能帮我一些指导/建议吗?

对不起,作为详细。谢谢!

+3

为什么要阻止UI线程?强制Silverlight中的所有内容使用异步IO的关键是阻止您阻止UI线程。只是不要这样做。反而思考 - 与平台一起而不是与之搏斗。 – 2012-07-16 16:14:01

+0

感谢您的意见,@JonSkeet。 – 2012-07-16 16:54:17

回答