I'm trying to use the async HttpWebRequest
in Silverlight for Windows Phone. All works perfect until I get to the where I should call
private static ManualResetEvent allDone = new ManualResetEvent(false);
...
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
allDone.WaitOne();
Debug.WriteLine("All done!");
In GetResponseCallback
:
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
allDone.Set();
}
catch (Exception e)
{
Debug.WriteLine("Got Exception in GetResponseCallback: " + e.Message);
}
}
After the call to allDone.WaitOne();
it just hangs...
Any suggestions on why?
This just takes a bit of a shift in thinking away from blocking/waiting to thinking in async terms on the WP7 platform. The result is the user is always able to interact with the UI.
Move a call to your completion code (writeline in this case) into your CompletedEventHandler and for any UI updates marshall back to the UI thread with
Dispatcher.BeginInvoke( () => { /* your UI update code */ } )
If there are any UI elements that should not be interacted with while your async op is executing then these controls can be hidden or disabled for the interim.
To be honest, this isn't a good idea. Having the wait on the main (UI) thread will lock the phone up and create an unresponsive UI. It'll be better in the long run not to fight the async network access in WP7 and Silverlight, the code can be more complex in places and you end up having a lot of methods that take call backs, but having a more response UI is better than having it lock up.
var request = WebRequest.CreateHttp(uri);
request.BeginGetResponse(r =>
{
var reponse = request.EndGetResponse(r);
// Do things response here
}, null);
// Let the method end and not wait
I encountered the same issue but is resolved when i replaced the WP7 image with new one. Unlocked image will cause this issue.
It appears to be a limitation of the emulator. I haven't tried this out yet but I believe running this on an unlocked wp7 emulator should do the trick. http://forum.xda-developers.com/showthread.php?p=11148176#post11148176
Also note that if the ManualResetEvent never occurs this call to WaitOne will never return:
http://msdn.microsoft.com/en-us/library/bb299385.aspx
You probably want to move allDone.Set()
outside the try..catch
. Otherwise the event will never be set if there's an exception and the thread that started the async operation will hang. That is, you want to write:
try
{
request = (HttpWebRequest)asynchronousResult.AsyncState;
response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
}
catch (Exception e)
{
Debug.WriteLine("Got Exception in GetResponseCallback: " + e.Message);
}
allDone.Set();