Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

c# - Parallel task run with async and await - unable to use multiples cores

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.

Is it possible?

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();
    }
}

Thanks for all the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...