I'm creating a library that contains a class that exposes several Async methods:
public class MyClass {
public async Task<Foo> DoFooAsync() { /*...*/ }
public async Task<Bar> DoBarAsync() { /*...*/ }
}
I have two (main) questions about this:
I understand that not everybody likes to (or needs to) work asynchronously; it's easy for someone using my library to invoke these methods synchronously. However, it won't be very much of an effort to provide synchronous wrappers for the async method so that the class also provides a
public Foo DoFoo()
andpublic Bar DoBar()
method.- Should I provide these methods or should I let people implement their own?
- If I provide these methods, should I:
- Create a
private T ExecuteFunctionSynchronously<T>(Func<T> func)
method and have the synchronous methods invoke thisExecuteFunctionSynchronously
internally or ... - ...should every synchronous method just call the async method 'waterfall style' (so
DoFoo()
executesreturn DoFooAsync().Result
(or something like that) internally?
- Create a
The class will, later, have a 'message loop' which continually reads data coming from an (awaited) socket. I want this message loop to go on 'eternally'. I want the class to be easily used by everyone.
- What kind of 'style' should I use for this messageloop to notify users of MyClass that something has happened?
- Events (e.g.
MyClass.FooReceived += myhandler
)? - Callbacks (e.g.
MyClass.StartListening(myhandler)
)? - Something 'awaitable' (e.g.
while (await MyClass.GetFoo()) { ... }
)? - Reactive (Rx)?
- Something other than above, namely ...
- Events (e.g.
- What kind of 'style' should I use for this messageloop to notify users of MyClass that something has happened?
I'm primarily asking for "style" guidance; how would you approach this and how do you think a (primarily) async library should provide (API wise) interaction while keeping internals and messageloops out of the user's mind without exposing too much of what's going on internally.