异步不应该用于高CPU任务吗? [英] Is it true that async should not be used for high-CPU tasks?

查看:96
本文介绍了异步不应该用于高CPU任务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道async-await是否不应该用于高CPU"任务.我在演示文稿中看到了这一点.

I was wondering whether it's true that async-await should not be used for "high-CPU" tasks. I saw this claimed in a presentation.

所以我想那意味着

Task<int> calculateMillionthPrimeNumber = CalculateMillionthPrimeNumberAsync();
DoIndependentWork();
int p = await calculateMillionthPrimeNumber;

我的问题是 上面的说法是合理的,否则,是否还有其他使高CPU任务异步的示例?

My question is could the above be justified, or if not, is there some other example of making a high-CPU task async?

推荐答案

我想知道async-await是否不应该用于高CPU"任务.

I was wondering whether it's true that async-await should not be used for "high-CPU" tasks.

是的,是的.

我的问题是以上说法是否合理

My question is could the above be justified

我会说这是没有道理的.通常,应避免使用Task.Run来实现带有异步签名的方法. Don'公开用于同步方法的异步包装器.这是为了避免引起消费者的混淆,尤其是在ASP.NET上.

I would say that it is not justified. In the general case, you should avoid using Task.Run to implement methods with asynchronous signatures. Don't expose asynchronous wrappers for synchronous methods. This is to prevent confusion by consumers, particularly on ASP.NET.

但是,例如在UI应用程序中,使用Task.Run调用 同步方法没有任何问题.这样,您可以使用多线程(Task.Run)保持UI线程空闲,并使用await优雅地使用它:

However, there is nothing wrong with using Task.Run to call a synchronous method, e.g., in a UI app. In this way, you can use multithreading (Task.Run) to keep the UI thread free, and consume it elegantly with await:

var task = Task.Run(() => CalculateMillionthPrimeNumber());
DoIndependentWork();
var prime = await task;

这篇关于异步不应该用于高CPU任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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