Andrew B Schultz
Andrew B Schultz

Reputation: 1512

Using TPL Tasks with HttpWebRequest

I was hoping to use the System.Threading.Task library for my asynchronous web requests in my WP7 project. However, in WP7 (I believe) you have to use the HttpWebRequest class for http requests (something my app does a lot of). The HttpWebRequest class only has a BeginGetResponse method that forces you to use the old asynchronous programming model by requiring you to pass in a callback parameter.

Is there any way to enter modernity using WP7, or am I stuck with HttpWebRequests and callbacks?

UPDATE Jon gave me some good direction on finding the right method to convert APM code to TPL using Task.Factory.FromAsync, but I am really struggling on using Task.Factory.FromAsync. The first parameter is an IAsyncResult, which I assume would be your BeginGetResponse or BeginGetRequest method. But the second parameter, which the documentation I've read typically suggests should be your end method, is a Func. The EndGetRequest and EndGetResponse methods for HttpWebRequest return a Stream ... and at that point, I'm lost.

Upvotes: 3

Views: 1521

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502116

In general, you can use TaskFactory.FromAsync to build a Task<T> from a begin/end-method pair.

I don't know whether that's supported by the WP7 version of TPL, but it's where I'd start.

See also: "TPL and Traditional .NET Framework Asynchronous Programming".

Upvotes: 4

Related Questions