简体   繁体   English

返回任务时我不应该使用等待/异步吗?

[英]Should I not use await/async when returning Task?

When I want to create a method returning Task with I/O bound work I usually use something like this:当我想创建一个返回具有 I/O 绑定工作的 Task 的方法时,我通常使用这样的东西:

public async Task<ProductModel> GetProduct(string name, CancellationToken ct = default)
{
    //...
    return await GetAsync<ProductModel>(request, ct);
}

And call it like this:并这样称呼它:

var product = await GetProduct("some product", ct);

But I came across some function definition just like above but without the await/async :但是我遇到了一些 function 定义,就像上面一样,但没有await/async

public Task<ProductModel> GetProduct(string name, CancellationToken ct = default)
{
    //...
    return GetAsync<ProductModel>(request, ct);
}

With a similar call as mine.和我的电话类似。

My question is, is this latter definition safe, can I just suppress the await/async in the function returning a Task ?我的问题是,后一种定义是否安全,我可以在 function 返回一个Task中抑制await/async吗?

And if so, are there any benefits or drawbacks?如果是这样,有什么好处或缺点吗?

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

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