I’ve been moving some data access code to to use Lazy<T> whenever I want to defer actually fetching the data until it’s first needed. What I’ve always found interesting is there is no Lazy Async. In the exact use case it’s when an application loads, there is some static data loaded from a database. This data is the cached for later use. However, in many situations it’s not actually needed until much later if at all. Why take the performance hit of fetching the data on app startup if that data is often times not needed? That’s the whole purpose of Lazy<T>. But as mentioned, why is there no Lazy Async? If i want to defer IO, that’s generally async. Here is more info on Lazy Initialization if it’s new to you.
Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
4 thoughts to “Lazy Async”
AsyncLazy is available in Nito.AsyncEx if you would like an implementation from a widely used nuget package.
Awesome, thanks for the share!
It was also based on a blog post by Stephen Toub (https://blogs.msdn.microsoft.com/pfxteam/2011/01/15/asynclazyt/) where he explains why the Func<Task> is wrapped/unwrapped with StartNew (or Run), which is a subtle thing many people won’t get.
Hi Derek, found you site/blog on a Google search some time ago. It always a pleasure to hear from you your ‘code opinions’. Congrats!!