简体   繁体   中英

Is there any performance gain when using async in Data Access Layer?

I have a doubt that is there any performance gain if I use Async feature in Data Access Layer as below :

public async Task<IEnumerable<TrnApplicant>> GetAllMemberApplicantsAsync(String webReferenceNumber)
{
    using (var context = new OnlineDataContext())
    {
        var applicant = await Task.Run(() => context.Applicants.First(
                app => app.RefNo.Equals(webReferenceNumber, StringComparison.OrdinalIgnoreCase)) );

        return GetApplicantsInGroup(applicant.ApplicantsGroupId);
    }      
}

Also if not when does it make more sense?

Consider this.

You call someone and ask them to do something for you. While they do it, you wait on the line, waiting for them to say "It's done". This is synchronous work. The act of calling them "blocks" until they're done with the job, and then you can get back to whatever you were doing, afterwards .

The alternative, asynchronous way, would be for you to make the call, but instead of waiting on the phone you hang up, and do something else while they work. Once they call you back, saying "It's done", you go back to doing whatever you needed their results to do.

Now, if you have nothing to do while you wait, there will be absolutely no performance gain, instead quite the opposite. The overhead of having the other party call you back will instead add to the total amount of work to do.

So with the above description of asynchronous work, do you have anything your code could do while it waits for the data access layer to complete its job?

If not, then no, there would be no performance gain.

If yes, then there could be performance gains.


Now, having said all that, I read the comment below my answer, and then I re-read your code a bit more carefully, and I believe that you are not really taking advantage of proper asynchronous code here.

The best way would be for you to use some kind of system or code that does asynchronous I/O properly. Your code calls Task.Run , which is actually the same as just plunking a different person down in front of the phone, doing the waiting for you.

For instance, consider SqlCommand , which may be the actual code doing the talking to the database here, it has two interesting methods:

Now, if you call the first one, on a thread created with Task.Run , you are in effect still blocking, you're just asking someone else to do it for you.

The second, however, is as I described above.

So in your particular case I would try to avoid using Task.Run . Now, depending on the load of your server, there may be advantageous to do it like that, but if you can I would switch to using the asynchronous methods of the underlying objects to do it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM