I'm working on a class to download some data from an external server and feed it into my data model. I'm new to both HttpClient
and async
methods in C#, so I'm not sure of a few things.
- Is my placement of
new SearchResultSet()
reasonable? It's a little contrived, true, but I'm trying to get an example of how async code can streamline execution. - Is splitting the
GetStringAsync()
andawait myTask
statements going to cause any problems?
The HttpClient
class is being passed in via the constructor to aid in unit testing.
class MySearch
{
private readonly HttpClient searchClient;
private readonly Uri baseSearchUrl;
public MySearch(HttpClient client, Uri baseUrl) {
searchClient = client;
baseSearchUrl = baseUrl;
}
public async Task<SearchResultSet> SearchAsync(string term)
{
var query = "?gws_rd=ssl#q=" + term;
var searchUrl = new Uri(baseSearchUrl, query);
try {
var myTask = searchClient.GetStringAsync(searchUrl);
var result = new SearchResultSet()
{
SearchPageUrl = searchUrl
};
var searchData = await myTask;
result.Fill(searchData); //parsing HTML is off-topic for this class!
return result;
}
catch (AggregateException ex)
{
throw ex;
}
catch (WebException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
}