I’m trying to make multiple consecutive HttpWebRequest in WP7. Each one uses info (an ID from a cookie, an URL location for a redirect, some HTML…) from the previous one, so we need to “wait” until the previous one finishes before continue.
In Android, we make a new thread and then you go sequential with multiple Synchronous HttpPost or HttpGet, but here it’s different because of the async nature of Silverlight.
What I have right now is this in my helper class (instantiated on the UI Thread):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(theUrl);
request.Method = "POST";
try
{
IAsyncResult ias = request.BeginGetResponse(new AsyncCallback(getCookiesStatus), request);
}
catch (Exception e)
{
Console.Write("ERROR" + e.Message);
}
The getCookieStatus:
private void getCookiesStatus(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
ccCookies = response.Cookies;
HttpStatusCode sc = response.StatusCode;
if (sc == HttpStatusCode.Found)
{
location = response.Headers["Location"];
}
}
What would be the best way to use that “location” string we got to make another consecutive http request without chaining calls from function to function? Is there any way to raise a “waker” (an event?) in the UI thread after the IAsyncResult?
The async ctp is a new visual studio feature that provides some great syntactic sugar for exactly this type of asynchronous sequential workflow. It is unfortunately not suitable for production code yet as it’s still a technology preview.
Until then, you have to either chain callbacks (not awful for 2 or 3 operations but beyond that: spaghetti) or use something like a coroutine pattern implemented with iterators and generators.
Edit: @AnthonyWJones linked to another coroutine implementation using a generator in the comments above.