问题
Consider the following interface and implementations.
interface IService
{
Task<string> GetAnswer(string question);
}
class SomeService : IService
{
async Task<string> IService.GetAnswer(string question)
{
... code using awaits ...
}
}
class AnotherService : IService
{
Task<string> IService.GetAnswer(string question)
{
return Task.FromResult("I have no idea.");
}
}
According to the Microsoft naming conventions, should the interface method be named GetAnswer
or GetAnswerAsync
?
By convention, you append "Async" to the names of methods that have an Async or async modifier.
The problem is that the first implementation uses the async
modifier, indicating it should receive the "Async" method name suffix, but the second implementation does not use the async
modifier, indicating it should not receive the "Async" method name suffix. The two method names in the implementations are forced to be the same by the interface, so I am forced to violate the naming conventions for one of the two classes.
Note I'm not looking for opinionated answers. Consider it multiple choice. :)
- You should use the "Async" suffix because the naming conventions say so. (With reference.)
- You should not use the "Async" suffix because the naming conventions say so. (With reference.)
- The naming conventions don't say. (This will need to come from someone well-versed in them.)
回答1:
You should use XAsync
even when there isn't an async
modifier as long as the method represents a complete task based asynchronous operation.
To be technical about it, the passage you quoted tells you to add an Async when there is an async
modifier but doesn't tell what to do when there isn't any.
The async
modifier is really not a part of the method's signature and you could easily accomplish the exact same behavior without it. If you look at the Task-based Asynchronous Pattern you wouldn't find a reference to the specific async
modifier, but to the more broad definition of an async
method.
In the .Net framework itself, you can't even know which Async method actually uses the async
modifier. A lot (if not most) return TaskCompletionSource.Task
to allow you (as a user) to use async-await
. For example, this is Stream.WriteAsync:
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCancellation(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
来源:https://stackoverflow.com/questions/24766651/interface-naming-convention-for-method-returning-task