When a method uses a cache, but occasionally does I/O, should it return T, or Task<T>?

Viewed 112

So my question basically comes down to, should I return a Task, so the caller can be async, even if 99% of the time, there is no I/O?

Say my code is something like:

var countryList = _cacheService.Get<List<Country>>("Countries", LoadCountrys);

In this example, LoadCountrys is a method that will make the I/O call. So the first time this is called, it will do some I/O to load all the countries into a cache, then each call after that will just read from an in-memory cache (no I/O).

The method signature would look like:

List<Country> GetCountryList();

The other way to do this would be:

var countryList = await _cacheService.GetAsync<List<Country>>("Countries", LoadCountrysAsync);

The method signature would look like:

List<Country> GetCountryListAsync();

It seems wasteful to me, paying for the overhead of a Task, when most of the time the code is not truly async.

However in Joe Duffy's blog, in the section Variable latency and asynchrony, he goes on to say even if you rarely do I/O, you should still return a Task.

So are my gut instincts wrong? Or maybe the Task overhead is so small it doesn't matter? Or is this a "It depends" kind of answer?

2 Answers
Related