Task.Run()会对性能产生任何影响吗? [英] will Task.Run() make any difference in performance?

查看:617
本文介绍了Task.Run()会对性能产生任何影响吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用数据库的方法,如下所示:

I have a method which calls database as shown below:

调用DAO方法的BL方法:

    public async Task<List<Classes>> GetClassesAndAddRules(string classId)
    {
        var classData = await Task.Run( () => _daoClass.GetClasses(classId));

        //logic for adding rule
        //..................................
    }

DAO中的数据库调用:

   //*below method takes 1 second approx to return*
    public List<Classes> GetClasses(string id)
    {
        var retVal = new List<Classes>();

        using (var context = new test_db_context())
        {
            var rows = context.GetClassesById(id);
            foreach (ClassesDBComplexType row in rows)
            {
                retVal.Add(Mapper.Map<GetClassesByClassIdOut>(row));
            }
        }
        return retVal;
    }

使用 await 调用DAO方法是否有任何性能提升?

Is there any performance boost just my calling the DAO method using await ?

我的理解是GetClasses()将在单独的线程上调用,这样它就不会阻塞并继续处理其他内容.

My understanding is GetClasses() will be called on a separate thread so that it doesn't block and continue processing other stuff.

感谢您的帮助.

推荐答案

您发布的代码无法编译.从您的问题的标题来看,我假设您的通话实际上看起来像await Task.Run(() => _daoClass.GetClasses(classId));

The code you posted won't compile. From the title of your question, I'm assuming that your call actually looks like await Task.Run(() => _daoClass.GetClasses(classId));

在这种情况下,使用Task.Run 会对性能产生影响:这会更糟.

In that case, the use of Task.Run will make a difference in performance: it will be worse.

async在服务器端的作用是释放请求线程,而不是阻塞请求.您使用await Task.Run(...)所做的是通过在另一个线程上开始工作来释放请求线程 .换句话说,Task.Run代码执行 plus 线程封送处理的工作量相同.

The point of async on the server side is to free up the request thread instead of blocking it. What you're doing with await Task.Run(...) is to free up the request thread by starting work on another thread. In other words, the Task.Run code has the same amount of work to do plus thread marshaling.

这篇关于Task.Run()会对性能产生任何影响吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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