c# - 如何通过使用任务的 I/O 绑定(bind)工作正确利用粗粒度并发?

标签 c# .net-core async-await

最近我对 I/O Bound 和 Cpu Bound 工作使用什么感到有点困惑,到目前为止我得出的结论(随意更正)是:

-Task.Run() - CPU 密集型工作

-TaskCompletionSource - I/O 绑定(bind)工作

场景:

您被困在执行基于 i/o 的工作且顺序运行的方法中,并且无法编辑该方法,使其异步运行的最佳选择是什么?

//method example
//Purposely avoiding using the AsyncTask Version Of DownloadString In WebClient
public void Foo()=>new WebClient.DownloadString("https://google.com");

//-------

//here is the part of the code that I will be trying to execute Foo asynchronously
await Task.Run(()=>Foo()); //wouldn't this be the only way to run this method asynchronously even though Foo isn't doing CPU Bound Work?

最佳答案

What would be the best choice to make it run asynchronously?

在“正常”类型的应用程序中,当您不冒线程饥饿的风险时: Task.Run(()=>Foo()); 确实是唯一的方法使其异步。

在 ASP.NET 应用程序中,您应该更加关心使用的线程数量。使此与 Task.Run() 异步会请求额外的线程以阻止该线程。当您有其他工作可以同时运行时,这有助于缩短响应时间,但会损害应用程序的整体性能和可扩展性。

因此,在 Controller 操作中,一般来说:不要执行任何操作。硬着头皮阻塞当前线程,而不是仅仅为了等待而请求另一个线程。

关于c# - 如何通过使用任务的 I/O 绑定(bind)工作正确利用粗粒度并发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65988034/

相关文章:

c# - Insert-Statement 不起作用 - 没有错误消息

c# - 使用 DropBox api 时的进度条

c# - 如何在 Entity Framework Core 2 中播种?

mysql - Nodejs 异步/等待 MySQL 查询

c# - botbuilder 不等待来自 HTTP 响应的响应(使用 Restsharp)

c# - 如何在 C# 中将 numericupdown 控件添加到自定义属性网格?

c# - Asp.Net Identity 在种子方法中创建角色失败

c# - dotnet 从 VSTS 中的解决方案仅发布一个项目

azure - 如何使用 StackExchange.Redis 为 Azure Redis 缓存的所有 key 全局设置 key 过期值?

c# - FIle.ReadAll***Async/WriteAll***Async/AppendAll***Async 方法在哪里?