返回Task的方法的接口命名约定
本文关键字:命名约定 接口 方法 返回 Task | 更新日期: 2023-09-27 18:13:09
考虑以下接口和实现。
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.");
}
}
根据Microsoft的命名约定,接口方法应该命名为GetAnswer
还是GetAnswerAsync
?
按照约定,你要在带有Async或Async修饰符的方法名后面加上"Async"。
问题是,第一个实现使用async
修饰符,表明它应该接收"Async"方法名称后缀,但第二个实现没有使用async
修饰符,表明它不应该接收"Async"方法名称后缀。接口强制实现中的两个方法名相同,因此我被迫违反了两个类之一的命名约定。
注意我不是在寻找固执己见的答案。就当是多项选择题吧。:)
- 你应该使用"Async"后缀,因为命名惯例是这么说的。(参考。)
- 你不应该使用"Async"后缀,因为命名惯例是这么说的。(参考。)
- 命名约定没有说。(这需要来自精通它们的人。)
即使没有async
修饰符,只要该方法表示基于任务的完整异步操作,您也应该使用XAsync
。
从技术上讲,你引用的段落告诉你当是和async
修饰符时添加Async,但没有告诉你当不是时该怎么做。
async
修饰符实际上不是方法签名的一部分,没有它也可以很容易地完成完全相同的行为。如果您查看基于任务的异步模式,您将找不到对特定async
修饰符的引用,而是对async
方法的更广泛定义的引用。
在。net框架中,你甚至不知道哪个Async方法实际使用了async
修饰符。很多(如果不是大多数)返回TaskCompletionSource.Task
,以允许您(作为用户)使用async-await
。例如,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);
}