Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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 a double locking cache pattern.
Key Features of LazyCache:
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.
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.
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.
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.
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
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.
IronPDF is a powerful C# PDF library that allows generating, editing, and extracting content from PDF documents in .NET projects. Here are some key features:
HTML to PDF Conversion:
Convert HTML, CSS, and JavaScript content to PDF format.
Use the Chrome Rendering Engine for pixel-perfect PDFs.
Image and Content Conversion:
Convert images to and from PDF.
Extract text and images from existing PDFs.
Editing and Manipulation:
Set properties, security, and permissions for PDFs.
Add digital signatures.
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.
To start with, create a Console application using Visual Studio as below.
Provide Project Name.
Provide .NET version.
Install IronPDF package.
Install LazyCache package to add cached method calls.
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
IronPDF package requires a license to run and generate the PDF. Add the following 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
A trial license is available on IronPDF's trial license page.
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.
9 .NET API products for your office documents