I am working on creating some libraries for a project at work and I wanted to make sure I have this pattern correct. Assuming that the GetWidgets()
method is what I am going to be exposing, which is the preferred method for this? Is there any fundamental difference between these two methods?
The first uses async
/await
and Task
:
public async Task<List<Widget>> GetWidgets(DateTime date)
{
using (var httpClient = new HttpClient())
{
var feed = "http://example.org/feed";
var response = await httpClient.GetStringAsync(feed);
var items = await SomeOtherAsyncMethod(response);
return items.Where(item => item.StartDate.Date == date).ToList();
}
}
The alternative uses Task.Factory.StartNew()
and Result
:
public Task<List<Widget>> GetWidgets(DateTime date)
{
return Task.Factory.StartNew(() =>
{
using (var httpClient = new HttpClient())
{
var feed = "http://example.org/feed";
var response = httpClient.GetStringAsync(feed).Result;
var items = SomeOtherAsyncMethod(response).Result;
return items.Where(item => item.StartDate.Date == date).ToList();
}
});
}
And if the second version is correct, should I be naming it GetWidgetsAsync()
?