I am trying to execute an asynchronous request in my MonoTouch application. When I execute the following code, it behaves like the request starts, but it never seems to return. What am I doing wrong?
private void StartAsyncRequest()
{
try
{
// Asynchronously execute the query using HttpWebRequest
string url = GetUrl();
WebRequest request = WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(AsyncAttempt_Completed), request);
}
catch (Exception ex)
{
// Show error message here.
}
}
private void AsyncAttempt_Completed(IAsyncResult result)
{
try
{
// 1. Get the response from the service call
WebRequest request = (WebRequest)(result.AsyncState);
using (WebResponse response = request.EndGetResponse(result))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string temp = reader.ReadToEnd();
// Show temp value here.
}
}
}
catch (Exception ex)
{
// Show error message here.
}
}
Thank you!
Unless you have very specific requirements I strongly suggest you to use
WebClientoverWebRequest. This will handle a lot of things for you automagically and will be better (in most cases) wrt memory management.E.g. most of your code above can be replaced to
DownloadStringAsyncOtherwise your code looks fine. In fact I executed it inside an MonoTouch application and it runs without issue (once
GetUrlis replaced) and your callback is called.However your comments, not your code, makes me wonder if the call succeed network-wise but fails ui-wise. e.g.
The async callback will be called on a different thread. UIKit, like most existing UI toolkit, requires that all UI-related operations be done on the main (UI) thread. Not doing so will give you a lot of pain.
You can ensure that UI (or other) code is executing on the main (UI) thread by using
InvokeOnMainThread. See this article for more details.