Interface naming convention for method returning Task [closed]

戏子无情 提交于 2020-01-14 10:19:20

问题


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. :)

  1. You should use the "Async" suffix because the naming conventions say so. (With reference.)
  2. You should not use the "Async" suffix because the naming conventions say so. (With reference.)
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!