1

Hi I need to write a proper async web request function in C# to get some data in JSON format and deserialize it in strongly typed object. I came up with this solution:

public async Task<TReturnType> MakeAsyncRequest<TReturnType>(string url) where TReturnType : class
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        var response = await request.GetResponseAsync();
        var json = await Task.Run(() => ReadStreamFromResponse(response));
        var deserializedObject = await Task.Run(() => JsonConvert.DeserializeObject<TReturnType>(json));

        return deserializedObject;
    }
    catch (Exception)
    {
        // TODO: Handle exception here
        throw;
    }
}

private string ReadStreamFromResponse(WebResponse response)
{
    using (var responseStream = response.GetResponseStream())
    using (var sr = new StreamReader(responseStream))
    {
        return sr.ReadToEnd();
    }
}

And usage would be like this:

var myData = await MakeAsyncRequest<IEnumerable<SomeObject>>(http://example.com/api/?getdata=all);

The issue I'm facing is that sometimes my web request fires and never returns, is there a proper way to handle that? Maybe playing with timers is an option but I don't like to go there.

Also I would be thankful if you could improve on my function, maybe there is a better way to do things and I just don't see it.

Alias
  • 341
  • 2
  • 3
  • 14
  • 2
    Did you know that `HttpClient` has already async flavors to most request methods? – Matías Fidemraizer May 30 '16 at 15:40
  • 1
    `sometimes my web request fires and never returns` - is there any correlation between the web requests that "hang"? You're not [calling them in a blocking way](http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html), right? Regarding improvements, I'd recommend `HttpClient.GetStringAsync` and [not using `Task.Run`](http://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html). – Stephen Cleary May 30 '16 at 15:59

0 Answers0