并行任务以异步方式运行并等待-无法使用多核 [英] Parallel task run with async and await - unable to use multiples cores

查看:66
本文介绍了并行任务以异步方式运行并等待-无法使用多核的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多代码,说可以使用具有并行异步功能的多个内核,但是没有一个起作用.它总是卡在一个内核中.

I have searched a lot of codes saying that is possible to use multiple cores with parallel async, but none worked. It is always stuck in a single core.

有可能吗?

以下是使用推荐设置在多核中运行任务的代码,但这没有发生.

Bellow it is a code that uses the recommend setting for running task run in multiples cores, but it is not happening.

class Program
{
    static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            var tasks = Enumerable.Range(0, 1000000)
             .Select(i => Console.Out.WriteLineAsync((100000 * 10000).ToString()));

            await Task.WhenAll(tasks);
        }).GetAwaiter().GetResult();
    }
}

感谢所有帮助.

推荐答案

Console.Out正在访问的流从技术上讲公开了异步操作,但实际上并没有异步执行任何操作.实际上,所有异步方法都同步完成所有工作,因为写入控制台的速度是如此之快,以至于其他任何操作都将花费更长的时间.

The stream that is being accessed by Console.Out technically exposes asynchronous operations, but it doesn't actually execute any of them asynchronously. All of the asynchronous methods actually do all of their work synchronously, because writing to the console is just so fast that it would take longer to do anything else.

当然,即使您用实际具有异步实现的IO操作(例如网络IO)替换了该操作,由于该操作受IO限制,您仍然不太可能看到大量的CPU使用情况.除了启动IO操作外,CPU无需执行其他任何操作.如果您确实希望看到很多CPU核心可以完成很多工作,那么您的工作主要应该是CPU约束的工作.

Of course, even if you replaced that operation with an IO operation that actually had an asynchronous implementation (such as network IO) then you're still unlikely to see much CPU usage, because the operation is IO bound. The CPU needs to do nothing more than start the IO operation. If you actually want to see lots of CPU cores doing lots of work, your work needs to be primarily CPU bound work.

这篇关于并行任务以异步方式运行并等待-无法使用多核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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