.NET HELP

LazyCache C# (How It Works For Developers)

Published August 13, 2024
Share:

Caching is a fundamental technique in software development for improving performance by storing frequently accessed data in memory or a faster storage medium. In C#, LazyCache is a popular library that simplifies thread-safe cache implementation, making it easier for developers to leverage caching effectively in their applications for heavy load scenarios.

What is LazyCache?

LazyCache is an underlying caching provider library for .NET/ ASP.NET Core applications that provides a simple and intuitive API for caching data. It is available as a NuGet package and can be easily integrated into C# projects. The primary goal of LazyCache is to simplify caching implementation and reduce the boilerplate code required to manage cached information using double locking cache pattern.

Key Features of LazyCache:

  1. Simple API: LazyCache provides a straightforward API for adding, retrieving, and removing cached items. Developers can quickly integrate caching into their applications or web service calls without dealing with complex caching mechanisms.

  2. Automatic Expiration: LazyCache supports the automatic expiration of cached items based on configurable expiration policies. Developers can specify the expiration duration for cached items, and LazyCache removes expired items from the cache data.

  3. In-Memory Caching: LazyCache stores cached items in memory by default, making it suitable for scenarios where fast access to cached data is required. In-memory caching ensures low latency and high throughput for cached data access.

  4. Thread-Safe Operations: LazyCache provides thread-safe operations for adding, retrieving, and removing cached items. This ensures that multiple threads can access the cache concurrently without the risk of data corruption or inconsistency.

  5. Extensibility: LazyCache is designed to be extensible, allowing developers to customize caching behavior according to their specific requirements. It provides hooks for implementing custom caching strategies, such as distributed caching or caching with persistence.

How to Use LazyCache in C#:

Using LazyCache in C# is straightforward, thanks to its intuitive API. Below is a basic example demonstrating how to use LazyCache to cache the result of a method call:

using LazyCache;
public class DataService
{
// private readonly IAppCache cache
    private readonly IAppCache _cache;
    public DataService(IAppCache cache)
    {
        _cache = cache;
    }
    public string GetData()
    {
        return _cache.GetOrAdd("dataKey", () =>
        {
            // Simulate expensive operation such as database calls
            return FetchDataFromDatabase();
        });
    }
    private string FetchDataFromDatabase()
    {
        // Simulate fetching data from a database
        return "Cached Data";
    }
}
using LazyCache;
public class DataService
{
// private readonly IAppCache cache
    private readonly IAppCache _cache;
    public DataService(IAppCache cache)
    {
        _cache = cache;
    }
    public string GetData()
    {
        return _cache.GetOrAdd("dataKey", () =>
        {
            // Simulate expensive operation such as database calls
            return FetchDataFromDatabase();
        });
    }
    private string FetchDataFromDatabase()
    {
        // Simulate fetching data from a database
        return "Cached Data";
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

In this example, the DataService class uses LazyCache to cache the result of the GetData() method. The GetOrAdd() method retrieves the cached data associated with the specified key ("dataKey") if it exists. If the data is not cached, the provided delegate (FetchDataFromDatabase()) is executed to fetch the data, which is then cached for future use.

Introduction to IronPDF

LazyCache C# (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a powerful C# PDF library that allows to generate, edit, and extract content from PDF documents in .NET projects. Here are some key features:

  1. HTML to PDF Conversion:

    • Convert HTML, CSS, and JavaScript content to PDF format.

    • Use the Chrome Rendering Engine for pixel-perfect PDFs.
    • Generate PDFs from URLs, HTML files, or HTML strings.
  2. Image and Content Conversion:

    • Convert images to and from PDF.

    • Extract text and images from existing PDFs.
    • Support for various image formats.
  3. Editing and Manipulation:

    • Set properties, security, and permissions for PDFs.

    • Add digital signatures.
    • Edit metadata and revision history.
  4. Cross-Platform Support:

    • Works with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+).

    • Compatible with Windows, Linux, and macOS.
    • Available on NuGet for easy installation.

Generate PDF document Using IronPDF And LazyCache

To start with, create a Console application using Visual Studio as below.

LazyCache C# (How It Works For Developers): Figure 2 - Console App

Provide Project Name.

LazyCache C# (How It Works For Developers): Figure 3 - Project Configuration

Provide .NET version.

LazyCache C# (How It Works For Developers): Figure 4 - Target Framework

Install IronPDF package.

LazyCache C# (How It Works For Developers): Figure 5 - IronPDF

Install LazyCache package to add cached method calls.

LazyCache C# (How It Works For Developers): Figure 6 - LazyCache

using LazyCache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeSample
{
    internal class LazyCacheDemo
    {
        public static void Execute()
        {
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo LazyCache and IronPDF</h1>";
            content += "<h2>Create CachingService</h2>";
            // Create the cache service using caching logic
            IAppCache cache = new CachingService();
            content += "<p>IAppCache cache = new CachingService();</p>";
            var cacheKey = "uniqueKey";           
            content += "<p>string cachedValue = cache.GetOrAdd(cacheKey, expensiveMethod);</p>";
            // Define a factory method to generate the cacheable data
            Func<string> expensiveLongRunMethod = () => {
                var pdf = renderer.RenderHtmlAsPdf(content);
                // Export to a file or Stream
                pdf.SaveAs("AwesomeLazyCacheAndIronPdf.pdf");
                return content;
            };
            // Get the cached value or add it if it doesn't exist
            string cachedValue = cache.GetOrAdd(cacheKey, expensiveLongRunMethod);
            Console.WriteLine(cachedValue);
        }
    }
}
using LazyCache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeSample
{
    internal class LazyCacheDemo
    {
        public static void Execute()
        {
            // Instantiate Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo LazyCache and IronPDF</h1>";
            content += "<h2>Create CachingService</h2>";
            // Create the cache service using caching logic
            IAppCache cache = new CachingService();
            content += "<p>IAppCache cache = new CachingService();</p>";
            var cacheKey = "uniqueKey";           
            content += "<p>string cachedValue = cache.GetOrAdd(cacheKey, expensiveMethod);</p>";
            // Define a factory method to generate the cacheable data
            Func<string> expensiveLongRunMethod = () => {
                var pdf = renderer.RenderHtmlAsPdf(content);
                // Export to a file or Stream
                pdf.SaveAs("AwesomeLazyCacheAndIronPdf.pdf");
                return content;
            };
            // Get the cached value or add it if it doesn't exist
            string cachedValue = cache.GetOrAdd(cacheKey, expensiveLongRunMethod);
            Console.WriteLine(cachedValue);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Explanation

  • Instantiate Renderer: An instance of ChromePdfRenderer is created to handle the conversion of HTML content into PDF format.
  • Define Content: HTML content ("

    Demo LazyCache and IronPDF

    ", "

    Create CachingService

    ", etc.) is prepared. This content will be rendered into a PDF and cached for reuse.
  • Create Cache Service: A caching service (IAppCache) is instantiated using LazyCache's CachingService. This lazy cache service manages the storage and retrieval of cached data.
  • Cache Key: A unique identifier ("uniqueKey") is assigned to represent the cached PDF content.
  • Define Expensive Method: A factory method (expensiveLongRunMethod) is defined to generate the cacheable data. This method invokes the ChromePdfRenderer to render HTML content as a PDF. The resulting PDF is then saved and returned as a string.
  • Get or Add to Cache: The GetOrAdd method of the service is called to retrieve the cached value associated with the cacheKey. If the value doesn't exist in the cache, expensiveLongRunMethod is invoked to compute it, store it in the cache, and return it. If the value is already cached, it's returned directly.
  • Output: The cached PDF content (as a string) is printed to the console (Console.WriteLine(cachedValue)), demonstrating the retrieval of cached data.

Output

LazyCache C# (How It Works For Developers): Figure 7 - Console Output

PDF

LazyCache C# (How It Works For Developers): Figure 8 - PDF Output

IronPDF Licensing (Trial Available)

IronPDF package requires license to run and generate the PDF. Add below code at the start of the application before the package is accessed.

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Trial License is available here.

Conclusion

LazyCache simplifies caching implementation in C# applications by providing a straightforward API and automatic expiration of cached items. By integrating LazyCache into your projects, you can improve performance by efficiently caching frequently accessed data, reducing latency, and optimizing resource utilization in an atomic and tidy way. Whether you're building web applications, APIs, or services, LazyCache can be a valuable tool for enhancing the performance and scalability of your C# applications.

On the other hand, IronPDF stands out as a powerful and versatile C# library for handling PDF documents within .NET applications. Its robust capabilities encompass creating, editing, rendering HTML to PDF, and manipulating PDFs programmatically. With features for secure document handling through encryption and digital signatures, IronPDF empowers developers to efficiently manage and customize PDF workflows, making it a valuable tool for a wide range of document management and generation tasks in C# development.

< PREVIOUS
FluentEmail C# (How It Works For Developers)
NEXT >
DuckDB C# (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >