gpt4 book ai didi

c# - 嵌套的异步方法太多。那是问题吗?

转载 作者:行者123 更新时间:2023-12-04 04:08:46 30 4
gpt4 key购买 nike

以下代码从 3 个不同的资源中获取属于客户的投资列表。该流程以 Controller 的调用开始,并遵循下面描述的流程,其中所有方法都声明为异步并使用 await 运算符调用。

我想知道将所有方法设为异步是否有问题。是否有任何性能损失?是代码异味还是反模式?

我知道有些事情必须等待,比如访问 url、从 cahce 获取数据等。但我认为有些事情比如填充列表或汇总一些值不需要异步。

enter image description here

下面遵循代码(为清楚起见省略了某些部分):

Controller

    {HttpGet]
public async Task<IActionResult> Get()
{
Client client = await _mediator.Send(new RecuperarInvestimentosQuery());
return Ok(cliente);
}

查询处理程序
    public async Task<Client> Handle(RecoverInvestimentsQuery request, CancellationToken cancellationToken)
{
Client client;
List<Investiment> list = await _investimentBuilder.GetInvestiments();
client = new Cliente(request.Id, list);
return client;
}

投资 build 者
    public async Task<List<Investiment>> GetInvestiments()
{
ListInvestiments builder = new ListInvestiments();
await builder.BuildLists(_builder);
// here I get the List<Investiment> list already fulfilled to return to the controller
return list;
}

构建列表
    public async Task BuildLists(IBuilder builder)
{
Task[] tasks = new Task[] {
builder.GetFundsAsync(), //****
builder.ObterTesouro(),
builder.ObterRendaFixa()
};
await Task.WhenAll(tasks);
}

Funds, Bonds and Fixed Income Services (***这3种方法都是一样的,只是名字不同,所以为了节省篇幅,我只放了其中一种)
    public async Task GetFundsAsync()
{
var listOfFunds = await _FundsService.RecoverFundsAsync();
// listOfFunds will get all items from all types of investments
}

Recover Funds, Bonds 和 Fixed Incomes 方法也一样,我只是放了其中一种
    public async Task<List<Funds>> RecoverFundsAsync()
{
var returnCache = await _clientCache.GetValueAsync("fundsService");
// if not in cache, so go get from url
if (returnCache == null)
{
string url = _configuration.GetValue<string>("Urls:Funds");
var response = await _clienteHttp.ObterDadosAsync(url);
if (response != null)
{
string funds = JObject.Parse(response).SelectToken("funds").ToString();
await _clienteCache.SetValueAsync("fundService", funds);
return JsonConvert.DeserializeObject<List<Funds>>(fundos);
}
else
return null;
}
return JsonConvert.DeserializeObject<List<Funds>>(returnCache);
}

HTTP 客户端
    public async Task<string> GetDataAsync(string Url)
{
using (HttpClient client = _clientFactory.CreateClient())
{
var response = await client.GetAsync(Url);
if (response.IsSuccessStatusCode)
return await response.Content.ReadAsStringAsync();
else
return null;
}
}

缓存客户端
    public async Task<string> GetValueAsync(string key)
{
IDatabase cache = Connection.GetDatabase();
RedisValue value = await cache.StringGetAsync(key);
if (value.HasValue)
return value.ToString();
else
return null;
}

有人可以考虑一下吗?

提前致谢。

最佳答案

你的代码对我来说看起来不错。您正在使用 asyncawait只为 I/O和网络访问操作,它非常适合 async and await purposes:

  • 对于 I/O 绑定(bind)代码,您等待在异步方法中返回 Task 或 Task 的操作。
  • 对于受 CPU 限制的代码,您等待使用 Task.Run 方法在后台线程上启动的操作。

  • 一旦你使用了 asyncawait ,那么您的所有代码也趋于异步。这个事实在 MSDN 文章 - Async/Await - Best Practices in Asynchronous Programming 中有详细描述。 :

    Asynchronous code reminds me of the story of a fellow who mentioned that the world was suspended in space and was immediately challenged by an elderly lady claiming that the world rested on the back of a giant turtle. When the man enquired what the turtle was standing on, the lady replied, “You’re very clever, young man, but it’s turtles all the way down!” As you convert synchronous code to asynchronous code, you’ll find that it works best if asynchronous code calls and is called by other asynchronous code—all the way down (or “up,” if you prefer). Others have also noticed the spreading behavior of asynchronous programming and have called it “contagious” or compared it to a zombie virus. Whether turtles or zombies, it’s definitely true that asynchronous code tends to drive surrounding code to also be asynchronous. This behavior is inherent in all types of asynchronous programming, not just the new async/await keywords.

    关于c# - 嵌套的异步方法太多。那是问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62104283/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com