简体   繁体   English

非异步异步方法的命名约定是什么?

[英]What's the naming convention for non-async asynchronous method?

As is known to all, in C#, async methods are supposed to be named with suffix "Async" (eg ReadAsync , CreateAsync ). 众所周知,在C#中, async方法应该以后缀“ Async”命名(例如ReadAsyncCreateAsync )。

But in many cases, async/await is not necessary in an asynchronous method, for instance: 但是在许多情况下,异步方法中不需要async/await ,例如:

public async Task<string> DoSomethingAsync()
{
    return await GetAsync();
}

can be rewritten as: 可以重写为:

public Task<string> DoSomethingAsync()
{
    return GetAsync();
}

My question is: 我的问题是:

  1. For the situation above where async/await is totally optional, which version is the more correct? 对于以上情况,其中async/await完全是可选的,哪个版本更正确? Keep the async/await or return a Task directly? 保持async/await还是直接返回Task

  2. If the second version is better (returning a Task directly), should it conventionally still be named with suffix "Async" (ie DoSomethingAsync ) or not (ie DoSomething )? 如果第二个版本更好(直接返回一个Task ),按惯例还是应该使用后缀“ Async”(即DoSomethingAsync )命名(或者不命名)(即DoSomething )?

For the situation above where async/await is totally optional, which version is the more correct? 对于以上情况,其中async / await完全是可选的,哪个版本更正确? Keep the async/await or return a Task directly? 保持异步/等待还是直接返回任务?

I prefer returning a Task directly, but I've written an entire blog post on when this is appropriate and not . 我更喜欢直接返回Task ,但是我写了一篇完整的博客文章,说明什么时候合适,而不是什么时候

If the second version is better (returning a Task directly), should it conventionally still be named with suffix "Async" (ie DoSomethingAsync) or not (ie DoSomething)? 如果第二个版本更好(直接返回任务),则按惯例还是应使用后缀“ Async”(即DoSomethingAsync)命名(否)(即DoSomething)?

Yes. 是。 The Async suffix means "returns an awaitable". Async后缀的意思是“返回一个等待”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM