0

We're moving to .NET 4.5 and I'm considering adding async to my repositories:

interface IRepository<T>
{
    T Find(int id);
    Task<T> FindAsync(int id);
    IEnumerable<T> FindAll();
    Task<IEnumerable<T>> FindAllAsync();
    ...
}

Implementations will likely call DBs, WebServices, etc.

My question is, should I support CancellationToken?

(Don't worry - FindAllAsync() will probably be Rx-based :) )

i3arnon
  • 113,022
  • 33
  • 324
  • 344
n8wrl
  • 19,439
  • 4
  • 63
  • 103

2 Answers2

1

Well, definitely add async to your repositories. I'm all for async taking over the world. :)

CancellationToken support is another question. I generally do provide it if it's likely to be needed or if the underlying implementation (DB/web services) supports it (in that case, the implementation is so simple I'd rather just provide it).

Note that you can provide an overload without CancellationToken that just calls the primary implementation passing CancellationToken.None. Alternatively, you can give a default value on the interface of new CancellationToken() which is equivalent to CancellationToken.None. I used to use the default value approach all the time but there are some situations (like assigning an Action variable to myRepository.FindAllAsync) where overloads permit method resolution but default values do not.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
0

I was going to ask the same question. I'm starting to think the answer is "only if you believe cancellation is an important scenario". If you believe some repositories will take such a long time that a user or infrastructure service will want to cancel an in-process query, then you should. I can imagine that for a query, though one would think that most updates and inserts would happen very quickly. If they don't, it's likely because of an exceptional condition which would result in a failed (timed out?) task anyway.

Adding the support for CancellationToken will require all callers to provide one, which has a pernicious chaining effect.

Sebastian Good
  • 6,310
  • 2
  • 33
  • 57