I think you need to have a clear use-case for providing 'async versions' of existing methods. Classes written for synchronous execution often contain assumptions which can be violated when asynchrony comes into play. Asynchrony is after all multi-threading (or at least does not preclude the use of threads). Therefore naively wrapping the sync method in a task.run opens you up to the real possibility of threading bugs such as race conditions which do not occur in the single-threaded implementation.
Also to obtain any *actual* benefit from an async counterpart the implementation more than likely has to change. For example, a sync method might use the synchronous File API, whereas an async counterpart can gain benefit by using the async File API. The other thing to remember is that the client of GetThing is actually just as well placed as you are -- if not better placed -- to wrap your method up in a task.run. So why not just leave it to them if they want to go down that route? Tristan. On Fri, Mar 27, 2015 at 9:17 PM, Greg Keogh <[email protected]> wrote: > Folks, I have an existing library with lots of traditional non-async > methods in it, and I want to provide async versions of the old methods. > Would you consider this to be a simple and trustworthy way of getting this > done? > > public Thing GetThing(int key) > { > // This is the existing method > return ... > } > > public Task<Thing> GetThingAsync(int key) > { > return Task.Run(() => > { > return GetThing(key); > } > } > > So I just make matching pairs where the old methods are just wrapped in > Task.Run(...). It seems too easy. This is Framework 4.5, and I have a vague > recall that Task.Run doesn't work this easily in 4.0 and it's a bit more > verbose. > > *Greg K* >
