I have a method that tries to load data from multiple URLs into Parallel and returns IEnumerabledeserialized types
The method is as follows:
public IEnumerable<TContent> DownloadContentFromUrls(IEnumerable<string> urls)
{
var list = new List<TContent>();
Parallel.ForEach(urls, url =>
{
lock (list)
{
_httpClient.GetAsync(url).ContinueWith(request =>
{
var response = request.Result;
response.Content.ReadAsStringAsync().ContinueWith(text =>
{
var results = JObject.Parse(text.Result)
.ToObject<IEnumerable<TContent>>();
list.AddRange(results);
});
});
}
});
return list;
}
In my unit test (I end up _httpClient to return a known typing), I basically get
The sequence contains no elements.
This is because the method returns before tasks are completed.
If I add .Wait () to the end of my .ContinueWith () calls, it will pass, but I'm sure I'm using the API incorrectly here ...
source
share