Search code examples
c#asynchronoustapasync-ctp

How to properly call both TAP and non-TAP methods from same code?


I have class method A that needs to use the services of one of N calculator objects to do its job.

To keep A dumb and happy, I'm not going to ask it to figure out which calculator it needs to use; some higher level code is going to figure out which calculator A should be using, and inject it into A.

The problem I'm running in to is that some of these calculators are just hunks of non-TAP (sync code) and other calculators are methods that are marked "async" (TAP)

I can't figure out how to inject A with both TAP and non-TAP calculators. IE, for TAP calculators, it seems I need to do an "await", but for non-TAP calculators, I wouldn't.

Not sure how to approach this problem? Thanks


Solution

  • In general, if you're trying to move to an async model, I would recommend wrapping your synchronous methods into a Task<T> and making them asynchronous. You could then use async calls everywhere.

    IE, for TAP calculators, it seems I need to do an "await", but for non-TAP calculators, I wouldn't.

    It actually doesn't matter how this is implemented. A "non-TAP" calculator would return T, and a "TAP" calculator would return Task<T>. This is really the only difference - if your method is returning Task or Task<T>, you'd likely want to use await. If not, you'd either want to just use the value, or wrap it in TaskEx.Run (making it async) so that you could use await.