C#与任务异步比同步慢 [英] C# Asynchronous with task is slower than synchronous

查看:406
本文介绍了C#与任务异步比同步慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道为什么同步fibonacci方法比异步/等待更快,而又比异步任务快吗?

Do you know why sync fibonacci method is faster than async/await and that is faster than async task?

我在每种项目方法上都使用了异步,所以它是主要的这是如此糟糕的方法...

I used async on every project method, so it's main this is so bad approach...

代码:

        static int FibonacciSync(int number)
        {
            if (number == 0) { return 0; }
            else if (number == 1) { return 1; }
            else
            {
                var t1 = FibonacciSync(number - 1);
                var t2 = FibonacciSync(number - 2);
                return t1 + t2;
            }
        }

        async static Task<int> FibonacciAwait(int number)
        {
            if (number == 0) 
            { return 0; }
            else if (number == 1) 
            { return 1; }
            else
            {
                var task1 = FibonacciAwait(number - 1);
                var task2 = FibonacciAwait(number - 2);
                return (await task1) + (await task2);
            }
        }

        static Task<int> FibonacciAsync(int number)
        {
            if (number == 0) 
            { return Task.FromResult(0); }
            else if (number == 1) 
            { return Task.FromResult(1); }
            else
            {
                return FibonacciAsync(number - 1).ContinueWith(task1 =>
                {
                    return FibonacciAsync(number - 2).ContinueWith(task2 =>
                    {
                        return task1.Result + task2.Result;
                    });
                }).Unwrap();
            }
        }

结果:


  • 同步:00:00:00.0121900

  • 等待:00:00:00.2118170

  • 异步:00:00:02.6211660

推荐答案


同步fibonacci方法比异步/等待更快,并且比异步任务还快吗?

Do you know why sync fibonacci method is faster than async/await and that is faster than async task?

异步并不是要提高原始速度。如您所知,整个过程花费的时间更长。如果您使用不当(如您所做的那样),则实现零收益的事情会变得非常缓慢。

Asynchrony is not about improving raw speed. As you've discovered, it takes longer overall. If you use it poorly, as you have done, it makes things much, much slower for zero benefit.

这里的根本问题是您不了解什么是异步性是为了。 异步用于管理延迟。将这一事实内部化之后,就可以正确使用它了。

The fundamental problem here is that you don't understand what asynchrony is for. Asynchrony is for managing latency. Once you internalize that fact, you'll start using it correctly.

延迟是您 request 计算或副作用,以及完成的情况。

Latency is the gap in time between when you request a computation or side effect, and when the computation or side effect is complete.

例如,假设您正在计算的东西在计算上极其昂贵。例如,您正在计算一个非常复杂的图形,即使将整个核心专用于该图形,它也将花费30毫秒以上的时间进行计算。您不希望在执行计算时用户界面停顿,因此您可以将计算放到另一个线程上,将CPU专用于该线程,然后等待结果。 等待是指在等待高延迟操作完成时找到更多工作要做

For example, suppose you are computing something that is extremely computationally expensive. You're computing a really complicated graphic, for example, and it is going to take more than 30 milliseconds to compute even if you dedicate an entire core to it. You do not want your user interface to stall while you're doing the computation, so you can put the computation onto another thread, dedicate a CPU to that thread, and await the result. An await means "go find more work to do while I am waiting for a high latency operation to complete".

例如,假设您执行的操作虽然在计算上不昂贵,但需要等待外部资源。例如,您正在调用数据库,要花费30毫秒以上的时间才能得到结果。在这种情况下,您不想启动线程。该线程将进入睡眠状态等待结果!相反,您想使用数据库访问API的异步版本,并等待高延迟结果

For example, suppose you are doing something that is not computationally expensive but requires waiting on an external resource. You're calling into a database, for example, and it is going to take more than 30 ms to get the result back. In this case you do not want to spin up a thread. That thread is just going to sleep waiting for the result! Instead you want to use the async version of the database access API, and await the high latency result.

在您的示例中,您没有首先要进行高延迟的操作,所以等待它是没有意义的。您在这里所做的所有事情都是为运行时创建大量工作,以创建和管理工作队列,而这是您要付费却没有从中受益的工作。您的工作需要 nanoseconds

In your example you don't have a high-latency operation to begin with, so it makes no sense to await it. All you're doing there is creating a lot of work for the runtime to create and manage the work queues, and that is work you are paying for but getting no benefit from. Your work takes nanoseconds; only use asynchrony for jobs that take milliseconds or longer.

仅对需要毫秒或更长时间的作业使用异步。 >。异步提高了性能,因为它在等待高延迟结果出现时释放了一个线程来继续工作。如果没有高延迟结果,那么异步只会降低所有速度。

Only use async when you have a high-latency operation. Async improves performance because it frees up a thread to keep on doing work while it is waiting for a high-latency result to appear. If there is no high-latency result then async will just slow everything down.

这篇关于C#与任务异步比同步慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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