Sanjay Sutar
Sanjay Sutar

Reputation: 544

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

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.

Upvotes: 3

Views: 4443

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456407

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.

Upvotes: 6

Related Questions