developer tip

메서드 이름에 "Async"접미사를 사용하는 것은 'async'수정자를 사용하는지 여부에 따라 달라 집니까?

optionbox 2020. 9. 7. 08:02
반응형

메서드 이름에 "Async"접미사를 사용하는 것은 'async'수정자를 사용하는지 여부에 따라 달라 집니까?


"Async"로 메서드 이름을 접미사하는 규칙은 무엇입니까?

"Async"접미사 한정자 로 선언 된 메서드 에만 추가되어야 async합니까?

public async Task<bool> ConnectAsync()

아니면 메서드가 Task<T>또는 반환하는 것으로 충분 Task합니까?

public Task<bool> ConnectAsync()

Microsoft 문서에서도 진실이 모호하다고 생각합니다.

Visual Studio 2012 및 .NET Framework 4.5에서 async키워드 ( AsyncVisual Basic의 경우) 로 지정된 모든 메서드 는 비동기 메서드로 간주되며 C # 및 Visual Basic 컴파일러는 TAP를 사용하여 메서드를 비동기 적으로 구현하는 데 필요한 변환을 수행합니다. 비동기 메서드는 Task또는 Task<TResult>개체를 반환해야 합니다.

http://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx

그것은 이미 옳지 않습니다. 모든 메서드 async는 비동기식이므로 호출 스택의 맨 위에있는 메서드 (예 : Button_Click 또는)에 적합하지 않은 Task또는 Task<T>-를 반환해야합니다 async void.

물론 대회의 요점이 무엇인지 고려해야합니까?

Async접미사 규칙은 메서드가 대기 가능하다는 것을 API 사용자에게 전달하는 것이라고 말할 수 있습니다. 메서드가 기다릴 수 있으려면 Taskvoid 또는 Task<T>값 반환 메서드에 대해 반환해야합니다. 즉, 후자에만 접미사 가 붙을 수 있습니다 Async.

또는 Async접미사 규칙은 메서드가 즉시 반환 될 수 있음을 알리고 현재 스레드가 다른 작업을 수행하도록 포기하고 잠재적으로 경쟁을 유발할 수 있음을 알리는 것이라고 말할 수 있습니다.

이 Microsoft 문서 인용문은 다음과 같습니다.

규칙에 따라 Async 또는 async 한정자가있는 메서드 이름에 "Async"를 추가합니다.

http://msdn.microsoft.com/en-us/library/hh191443.aspx#BKMK_NamingConvention

반환하는 자신의 비동기 메서드 TaskAsync접미사 가 필요 하다는 사실도 언급하지 않습니다 . 우리 모두 동의한다고 생각합니다.


따라서이 질문에 대한 답은 둘 다일 수 있습니다. 두 경우 모두 추가 할 필요 Async와 방법에 async키워드를 돌려 TaskTask<T>.


나는 상황을 명확히하기 위해 Stephen Toub에게 요청할 것입니다.

최신 정보

그래서 했어요. 그리고 우리의 선한 사람이 쓴 글은 다음과 같습니다.

공용 메서드가 작업 반환이고 본질적으로 비동기 인 경우 (항상 완료 될 때까지 동 기적으로 실행되지만 어떤 이유로 여전히 작업을 반환하는 것으로 알려진 메서드와는 반대로) "Async"접미사가 있어야합니다. 그것이 지침입니다. 여기서 이름 지정의 주요 목표는 호출되는 메서드가 모든 작업을 동 기적으로 완료하지 못할 가능성이 있다는 것을 기능 소비자에게 매우 분명하게 만드는 것입니다. 물론 기능이 동기 및 비동기 메서드를 사용하여 노출되는 경우에도 도움이되므로 구분하기 위해 이름 차이가 필요합니다. 메서드가 비동기 구현을 달성하는 방법은 명명에 중요하지 않습니다. async / await가 컴파일러의 도움을받는 데 사용되는지 또는 System.Threading.Tasks의 형식과 메서드가 직접 사용되는지 여부 (예 :

물론 가이드 라인에는 항상 예외가 있습니다. 이름 지정의 경우 가장 주목할만한 것은 전체 유형의 이유가 비동기 중심의 기능을 제공하는 것입니다.이 경우 모든 메서드에 Async를 사용하는 것은 과도 할 수 있습니다 (예 : 다른 작업을 생성하는 Task 자체의 메서드). .

void 반환 비동기 메서드의 경우 호출자가 비동기 작업이 언제 완료되었는지 알 수있는 좋은 방법이 없기 때문에 공용 노출 영역에 두는 것은 바람직하지 않습니다. 그러나 무효 반환 비동기 메서드를 공개적으로 노출해야하는 경우 비동기 작업이 시작되고 있음을 전달하는 이름을 원할 가능성이 높으며 의미가 있으면 여기에 "Async"접미사를 사용할 수 있습니다. 이 사건이 얼마나 드문 지 감안할 때 나는 그것이 실제로 사례 별 결정이라고 주장합니다.

도움이 되길 바랍니다, 스티브

The succinct guidance from Stephen’s opening sentence is clear enough. It excludes async void because it is unusual to want to create a public API with such a design since the correct way to implement an asynchronous void is to return a plain Task instance and let the compiler to its magic. However, if you did want a public async void, then appending Async is advised. Other top-of-stack async void methods such as event handlers are usually not public and don’t matter/qualify.

For me, it tells me that if I find myself wondering about suffixing Async on an async void, I probably should turn it into an async Task so that callers can await it, then append Async.


I build a lot API-services and other applications that call others systems where most of my code is running asynchronous.

My own rule of thumb I'm following is:

If there is both non-async and async method that return the same thing I suffix the async one with Async. Otherwise not.

Examples:

Only one method:

public async Task<User> GetUser() { [...] }

Same method with two signatures:

public User GetUser() { [...] }

public async Task<User> GetUserAsync() { [...] }

This makes sense since it's the same data that is returned but the only thing that differs is the way of returning data, not the data itself.

I also think this naming conventions exists due to the need to introduce async methods and still maintain backwards compatibility.

I argue that new code shouldn't use the Async suffix. It is just as obvious as return type of String, or Int as mentioned before in this thread.


What is the convention for suffixing method names with "Async".

The Task-based Asynchronous Pattern (TAP) dictates that methods should always return a Task<T> (or Task) and be named with an Async suffix; this is separate from the use of async. Both Task<bool> Connect() and asyncTask<bool> Connect() will compile and run just fine, but you won't be following the TAP naming convention.

Should the method contain the async modifier, or it enough that it just returns Task?

If the body of the method (regardless of the return type or name) includes await, you must use async; and the compiler will tell you "The 'await' operator can only be used within an async method. ...". Returning Task<T> or Task is not "enough" to avoid using async. See async (C# Reference) for details.

I.e. which of these signatures are correct:

Both asyncTask<bool> ConnectAsync() and Task<bool> ConnectAsync() properly follow the TAP conventions. You could always use the async keyword, but you'll get a compiler warning "This async method lacks 'await' operators and will run synchronously. ..." if the body doesn't use await.


or it enough that it just returns Task?

That. The async keyword isn't the real issue here. If you implement the asynchrony without using the async keyword the method is still "Async", in the general sense.


Since Task and Task<T> are both awaitable types, they represent some asynchronous operation. Or at least they should represent.

You should add suffix Async to a method which, in some cases (not necessarily all), doesn't return a value but rather returns a wrapper around an ongoing operation. That wrapper is usually a Task, but on Windows RT it can be IAsyncInfo. Follow your gut feeling and remember that if a user of your code sees the Async function, he or she will know that the invocation of that method is decoupled from the result of that method and that they need to act accordingly.

Note that there are methods such as Task.Delay and Task.WhenAll which return Task and yet don't have the Async suffix.

Also note that there are async void methods which represent fire and forget asynchronous method and you should better be aware that the method is built in such way.


I would argue that it should use the Async-suffix if it returns a Task regardless if the method is declared with the async modifier or not.

The reason behind it being that the name is declared in the interface. The interface declares the return type which is a Task. Then there are two implementations of that interface, one implementation implements it using the async modifier, the other does not.

public interface IFoo
{
    Task FooAsync();
}

public class FooA : IFoo
{
    public Task FooAsync() { /* ... */ }
}

public class FooB : IFoo
{
    public async Task FooAsync() { /* ... */ }
}

In Asynchronous Programming with async and await (C#), Microsoft offers the following guidance:

Naming Convention

By convention, you append "Async" to the names of methods that have an async modifier.

You can ignore the convention where an event, base class, or interface contract suggests a different name. For example, you shouldn’t rename common event handlers, such as Button1_Click.

I find this guidance incomplete and unsatisfying. Does this mean that in the absence of the async modifier, this method should be named Connect instead of ConnectAsync?

public Task<bool> ConnectAsync()
{
    return ConnectAsyncInternal();
}

I don't think so. As indicated in the concise answer by @Servy and the more detailed answer by @Luke Puplett, I believe that it is appropriate and indeed expected that this method should be named ConnectAsync (because it returns an awaitable). In further support of this, @John Skeet in this answer to another question appends Async to the method name regardless of the presence of the async modifier.

Finally, on another question, consider this comment by @Damien_The_Unbeliever:

async/await are implementation details of your methods. It matters not one jot whether your method is declared async Task Method() or just Task Method(), so far as your callers are concerned. (In fact, you are free to change between these two at a later point in time without it being considered a breaking change.)

From that, I infer that it is the asynchronous nature of the method that dictates how it should be named. The user of the method won't even know whether the async modifier is used in its implementation (without the C# source code or CIL).

참고URL : https://stackoverflow.com/questions/15951774/does-the-use-of-the-async-suffix-in-a-method-name-depend-on-whether-the-async

반응형