方法返回任务的接口命名约定

时间:2014-07-15 19:32:14

标签: c# .net interface naming-conventions async-await

考虑以下界面和实现。

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.");
    }
}

根据the Microsoft naming conventions,接口方法应该命名为GetAnswer还是GetAnswerAsync

  

按照惯例,您将“Async”附加到具有Async或async修饰符的方法的名称。

问题是第一个实现使用async修饰符,表明它应该接收“Async”方法名称后缀,但第二个实现不使用async修饰符,表明它不应该收到“Async”方法名称后缀。实现中的两个方法名称被接口强制相同,因此我不得不违反两个类之一的命名约定。

注意我不是在寻找固执己见的答案。考虑多选。 :)

  1. 您应该使用“Async”后缀,因为命名约定会这样说。 (参考。)
  2. 您不应该使用“Async”后缀,因为命名约定会这样说。 (参考。)
  3. 命名惯例没有说明。 (这需要来自精通他们的人。)

1 个答案:

答案 0 :(得分:5)

即使没有XAsync修饰符,您也应该使用async,只要该方法代表基于完整任务的异步操作。

要掌握相关技术,您引用的段落告诉您在 async修饰符时添加异步,但在 isn时不会告诉您该怎么做't 任何。

async修饰符实际上不是方法签名的一部分,如果没有它,您可以很容易地完成相同的行为。如果您查看Task-based Asynchronous Pattern,则无法找到对特定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);
}
相关问题