I'm working on a system in which multiple client objects are expected to implement a particular function via an interface, and I want that function to run asynchronously with continuations (I'm expecting the implementations to be I/O-bound and want to ensure that all the client objects complete this function as soon as possible). I'm using the Visual Studio Async CTP Refresh for SP1, with C# "5.0".
What is the recommended practice for enforcing asynchronous behavior in child objects of my abstract class (see below)? I can't (apparently) enforce use of 'async' methods using the virtual method approach. I can only require a 'Task' return type. Does this mean I should not try to require asynchronous behavior at all in child objects? In that case, should the return type be simply 'void'?
The public interface is an unfortunate consequence of the system design right now, but that's a separate issue. Obviously, I couldn't constrain anyone to be asynchronous who bypasses 'BaseFoo' and just implements the 'IFoo' interface.
Here is the code:
public interface IFoo
{
void Bar(); //NOTE: Cannot use 'async' on methods without bodies.
}
public abstract class BaseFoo : IFoo
{
public async void Bar()
{
await OnBar(); //QUESTION: What is the right "async delegation" pattern?
}
protected virtual async Task OnBar()
{
await TaskEx.Yield();
}
}
public class RealFoo : BaseFoo //NOTE: May be implemented by 3rd party
{
protected override async Task OnBar()
{
//CLIENT: Do work, potentially awaiting async calls
await TaskEx.Yield(); //SECONDARY QUESTION: Is there a way to avoid this if there are no 'awaits' in the client's work?
}
}
Whether a method is implemented using async
/await
or not is an implementation detail. How the method should behave is a contract detail, which should be specified in the normal way.
Note that if you make the method return a Task
or a Task<T>
, it's more obvious that it's meant to be asynchronous, and will probably be hard to implement without being asynchronous.
On the other hand, if there's an implementation (e.g. for test purposes) where the await
expressions would never be incomplete, why would you want to force someone to write an async method with no await
calls in anyway? You're expecting implementations to be IO-bound, but maybe there will be special cases where implementations want to use hard-coded data etc.
Basically you've got to handle this in the documentation for the method - if you can't trust implementers to read that, you've got no chance anyway :(
In addtion to Jon's answer, if you are following the Task-based Asynchronous Pattern then your method names should be suffixed with Async
, which self documents that it is an asynchronous method.
If you're implementing an interface
public interface IFoo
{
Task BarAsync();
}
it should be obvious that this should be implemented with the async
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With