Kiran
Kiran

Reputation: 3047

How to fix my WebAPI2 controllers to use async Task for scability

We have recently developed an ASP.Net WebAPI2 that is using the synchronous calls across various layers as below.

enter image description here

Now I have learnt that it's best to use the Async Task approach for stability reasons but as the code is already developed for most of the functionality using sync calls, I was wondering what is the best way to convert the calls I have.

Say this is how my code is initially written:

[Route("user/{userId}/feeds ")]
[HttpGet]
public IEnumerable<NewsFeedItem> GetNewsFeedItemsForUserAsync(string userId)
{
    return newsFeedService.GetNewsFeedItemsForUser(userId);
}

I can convert this to something like this:

[Route("user/{userId}/feeds ")]
[HttpGet]
public async Task<IEnumerable<NewsFeedItem>> GetNewsFeedItemsForUserAsync(string userId)
{
    return await Task.Run(()=>newsFeedService.GetNewsFeedItemsForUser(userId));
}

But, if I understand correctly, I don't think that will help me scale up my website as it will still end up using the thread pool thread.

The only other option I see to modify all the layers and all the functions to use async but that seems like a lot of work.

So I was wondering if anyone here had to undergo a similar exercise and what is the best way to address the problem.

Regards Kiran

Upvotes: 4

Views: 117

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

only other option I see to modify all the layers and all the functions to use async but that seams like a lot of work.

You're right, writing up a whole new data access layer that exposes true asynchronous methods is hard work, as it usually needs to be re-written from the ground up. But, if you know you actually need scalability and you've identified it as your current bottleneck, then it will end up being worth it.

Wrapping your code in Task.Run will benefit nothing, as you stated yourself, because what async does exactly is free a thread-pool thread while it does IO, where here you're actually consuming another thread, other than the one that ASP.NET runtime already provided you with.

To conclude, there is no easy magic fix to make this all work, it will require you to re-write/add async endpoints to the calling code.

Upvotes: 3

Related Questions