避免异步传播到方法签名中 [英] Avoid async from spreading in method signatures

查看:78
本文介绍了避免异步传播到方法签名中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阻止我在.net代码中不断使用异步/等待模式的原因是,一旦创建了异步方法,async关键字就会在我的代码中散布开来,迫使我使所有方法都异步.有没有一种模式可以有效地阻止这种情况?

What prevents me from constantly using the async/wait pattern in my .net code is that once you create an async method the async keyword tends to spread thru my code forcing me to make all methods async. Is there a pattern to stop this efficiently?

推荐答案

阻止我在.net代码中不断使用异步/等待模式的原因是,一旦创建了异步方法,async关键字就会在我的代码中散布开来,迫使我使所有方法都异步.有没有一种模式可以有效地阻止这种情况?

What prevents me from constantly using the async/wait pattern in my .net code is that once you create an async method the async keyword tends to spread thru my code forcing me to make all methods async. Is there a pattern to stop this efficiently?

那么,让我问你一个问题:为什么要使用async/await?您需要退后一步,然后确定是否需要异步代码的好处.如果您确实希望获得这些好处,那么您的代码必须是异步的. 一旦阻塞线程,您将失去异步的所有好处.那么,实际上,如果仍然要阻塞线程,为什么还要使用异步代码呢?

Let me ask you this, then: why are you using async/await? You need to take a step back and decide if you want the benefits of asynchronous code. If you do want those benefits, then your code must be asynchronous. As soon as you block a thread, you lose all the benefits of async. So really, why use asynchronous code at all, if you're just going to block a thread anyway?

也就是说,在某些情况下,部分async堆栈是有意义的.例如,如果您的代码库临时处于过渡状态.在这种情况下,您可以使用我在:

That said, there are some scenarios where a partially-async stack makes sense. For example, if your code base is temporarily in a transition state. In this case, you can use one of the hacks described in my article on brownfield async:

  • 直接阻止(可能导致死锁).
  • 阻塞线程池线程(在不同线程和不同上下文上执行代码,可能会导致意外的并行性).
  • 使用线程池上下文在当前线程上进行阻塞(在不同的上下文中执行代码,可能会导致意外的并行性).
  • 在具有单线程上下文的线程上阻塞(在不同线程和不同上下文上执行代码).
  • 阻止嵌套消息循环(可能导致意外重入).

所有这些都是hack,它们都有不同的缺点.没有适用于每种情况的hack.

All of these are hacks, and all have different drawbacks. There is no hack that works in every scenario.

这篇关于避免异步传播到方法签名中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆