will Task.Run() make any difference in performance?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 02:55:08

问题


I have a method which calls database as shown below:

BL Method to call DAO method:

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

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

DatabaseCall in 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;
    }

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

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

Any help is appreciated.


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/18038776/will-task-run-make-any-difference-in-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!