Shadow
Shadow

Reputation: 2478

C# caching and async requests

In this method:

private async List<stuff> GetData()
{
    return await _appCache.GetAsync("SiteStructurePages",
         () => _repository.GetSomeStuff());
}

is there any reason to keep it async? My code will execute in async manner just once, and all subsequent requests will use cache. Async spreads up to other parts of my application, that doesn't hit database, because lots of stuff is cached.

Edit: My application is IIS website application.

Upvotes: 1

Views: 110

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

is there any reason to keep it async?

That really depends on you. If you actually need to take advantage of asynchronous operations, which is being able to scale, then do keep it. Otherwise, if you don't, use a synchronous API. it's all up to you and what you actually make use of in your code base.

I understand the fact that you're worried about async methods going "all the way" and actually altering your entire code-base to become async. That's why you should do it as long as it's worth it.

Side note - you can slightly modify your code to save yourself the async state-machine generation:

private Task<List<stuff>> GetData()
{
    return _appCache.GetAsync("SiteStructurePages",
         () => _repository.GetSomeStuff());
}

Upvotes: 2

Russ Clarke
Russ Clarke

Reputation: 17909

If you can ensure that the call is quick and that it's not going to block a UI thread, then sure, you don't need Async on this one.

However, if such things are not in your control, then I would leave it asynchronous.

Upvotes: 0

Related Questions