跳至页脚内容
.NET 帮助

LazyCache C#(开发者用法)

缓存是软件开发中一项基本技术,通过将频繁访问的数据存储在内存或更快的存储介质中来提高性能。 在C#中,LazyCache是一个流行的库,该库简化了线程安全的缓存实现,使开发人员能够在高负载情况下有效利用缓存。

什么是LazyCache?

LazyCache 是一个用于 .NET/ ASP.NET Core 应用程序的基础缓存提供库,提供了简单直观的缓存数据 API。 它可作为 NuGet 包使用,可以轻松集成到 C# 项目中。 LazyCache 的主要目标是简化缓存实现,减少使用双重锁定缓存模式管理缓存信息所需的样板代码。

LazyCache 的主要功能:

  1. 简单 API: LazyCache 提供了一个简单的 API,用于添加、检索和删除缓存项。 开发人员可以快速将缓存集成到他们的应用程序或 Web 服务调用中,而无需处理复杂的缓存机制。

  2. 自动过期: LazyCache 支持基于可配置过期策略的缓存项自动过期。 开发人员可以指定缓存项的过期时长,LazyCache 会从缓存数据中删除过期项。

  3. 内存缓存: LazyCache 默认将缓存项存储在内存中,适用于需要快速访问缓存数据的场景。 内存缓存确保缓存数据访问的低延迟和高吞吐量。

  4. 线程安全操作: LazyCache 提供线程安全的操作,用于添加、检索和删除缓存项。 这确保了多个线程可以并发地访问缓存而不会有数据损坏或不一致的风险。

  5. 可扩展性: LazyCache 设计为可扩展,允许开发人员根据其特定需求定制缓存行为。 它提供了实现自定义缓存策略的钩子,例如分布式缓存或带有持久性的缓存。

在 C# 中如何使用 LazyCache:

由于其直观的 API,使用 C# 中的 LazyCache 很简单。 以下是一个基本的示例,演示如何使用 LazyCache 缓存方法调用的结果:

using LazyCache;

public class DataService
{
    // Define a private readonly field for the cache
    private readonly IAppCache _cache;

    // Constructor to initialize the cache
    public DataService(IAppCache cache)
    {
        _cache = cache;
    }

    // Method to retrieve data (cached or fetched)
    public string GetData()
    {
        return _cache.GetOrAdd("dataKey", () =>
        {
            // Simulate expensive operation such as database calls
            return FetchDataFromDatabase();
        });
    }

    // Simulate fetching data from a database
    private string FetchDataFromDatabase()
    {
        return "Cached Data";
    }
}
using LazyCache;

public class DataService
{
    // Define a private readonly field for the cache
    private readonly IAppCache _cache;

    // Constructor to initialize the cache
    public DataService(IAppCache cache)
    {
        _cache = cache;
    }

    // Method to retrieve data (cached or fetched)
    public string GetData()
    {
        return _cache.GetOrAdd("dataKey", () =>
        {
            // Simulate expensive operation such as database calls
            return FetchDataFromDatabase();
        });
    }

    // Simulate fetching data from a database
    private string FetchDataFromDatabase()
    {
        return "Cached Data";
    }
}
Imports LazyCache

Public Class DataService
	' Define a private readonly field for the cache
	Private ReadOnly _cache As IAppCache

	' Constructor to initialize the cache
	Public Sub New(ByVal cache As IAppCache)
		_cache = cache
	End Sub

	' Method to retrieve data (cached or fetched)
	Public Function GetData() As String
		Return _cache.GetOrAdd("dataKey", Function()
			' Simulate expensive operation such as database calls
			Return FetchDataFromDatabase()
		End Function)
	End Function

	' Simulate fetching data from a database
	Private Function FetchDataFromDatabase() As String
		Return "Cached Data"
	End Function
End Class
$vbLabelText   $csharpLabel

在此示例中,DataService 类使用 LazyCache 缓存 GetData() 方法的结果。 GetOrAdd() 方法在指定的键("dataKey")存在时,检索相应的缓存数据。 如果数据未缓存,将执行提供的委托FetchDataFromDatabase()来获取数据,然后为将来使用进行缓存。

IronPDF简介

LazyCache C#(开发人员如何使用):图1 - IronPDF

IronPDF 是一个强大的 C# PDF 库,允许在 .NET 项目中生成、编辑和从 PDF 文档中提取内容。 以下是一些关键功能:

  1. HTML 转 PDF 转换

    • 将HTML、CSS和JavaScript内容转换为PDF格式。
    • 使用Chrome呈现引擎获得像素完美的PDF。
    • 从 URL、HTML 文件或 HTML 字符串生成 PDF。
  2. 图像和内容转换

    • 将图像转换为PDF或从PDF转换图像。
    • 从现有PDF中提取文本和图像。
    • 支持各种图像格式。
  3. 编辑和操作

    • 设置PDF的属性、安全性和权限。
    • 添加数字签名。
    • 编辑元数据和修订历史。
  4. 跨平台支持

    • 适用于 .NET Core(8、7、6、5 和 3.1+)、.NET Standard(2.0+)和 .NET Framework(4.6.2+)。
    • 兼容 Windows、Linux 和 macOS。
    • 通过 NuGet 提供便捷安装。

使用 IronPDF 和 LazyCache 生成 PDF 文档

首先,使用 Visual Studio 创建一个控制台应用程序,如下所示。

LazyCache C#(开发人员如何使用):图2 - 控制台应用程序

提供项目名称。

LazyCache C#(开发人员如何使用):图3 - 项目配置

提供 .NET 版本。

LazyCache C#(开发人员如何使用):图4 - 目标框架

安装IronPDF包。

LazyCache C#(开发人员如何使用):图5 - IronPDF

安装 LazyCache 包以添加缓存的方法调用。

LazyCache C#(开发人员如何使用):图6 - LazyCache

using LazyCache;
using IronPdf; // Add the IronPdf namespace
using System;

namespace CodeSample
{
    internal class LazyCacheDemo
    {
        public static void Execute()
        {
            // Instantiate the Chrome PDF Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo LazyCache and IronPDF</h1>";
            content += "<h2>Create CachingService</h2>";

            // Create the cache service using LazyCache
            IAppCache cache = new CachingService();

            var cacheKey = "uniqueKey"; // Unique key for caching the content

            // Define a factory method to generate the cacheable data
            Func<string> expensiveLongRunMethod = () =>
            {
                // Render the HTML content to a PDF
                var pdf = renderer.RenderHtmlAsPdf(content);

                // Export the rendered PDF to a file
                pdf.SaveAs("AwesomeLazyCacheAndIronPdf.pdf");

                // Return the content as a string
                return content;
            };

            // Get the cached value or execute expensiveLongRunMethod to cache it
            string cachedValue = cache.GetOrAdd(cacheKey, expensiveLongRunMethod);

            // Output the cached value to the console
            Console.WriteLine(cachedValue);
        }
    }
}
using LazyCache;
using IronPdf; // Add the IronPdf namespace
using System;

namespace CodeSample
{
    internal class LazyCacheDemo
    {
        public static void Execute()
        {
            // Instantiate the Chrome PDF Renderer
            var renderer = new ChromePdfRenderer();
            var content = "<h1>Demo LazyCache and IronPDF</h1>";
            content += "<h2>Create CachingService</h2>";

            // Create the cache service using LazyCache
            IAppCache cache = new CachingService();

            var cacheKey = "uniqueKey"; // Unique key for caching the content

            // Define a factory method to generate the cacheable data
            Func<string> expensiveLongRunMethod = () =>
            {
                // Render the HTML content to a PDF
                var pdf = renderer.RenderHtmlAsPdf(content);

                // Export the rendered PDF to a file
                pdf.SaveAs("AwesomeLazyCacheAndIronPdf.pdf");

                // Return the content as a string
                return content;
            };

            // Get the cached value or execute expensiveLongRunMethod to cache it
            string cachedValue = cache.GetOrAdd(cacheKey, expensiveLongRunMethod);

            // Output the cached value to the console
            Console.WriteLine(cachedValue);
        }
    }
}
Imports LazyCache
Imports IronPdf ' Add the IronPdf namespace
Imports System

Namespace CodeSample
	Friend Class LazyCacheDemo
		Public Shared Sub Execute()
			' Instantiate the Chrome PDF Renderer
			Dim renderer = New ChromePdfRenderer()
			Dim content = "<h1>Demo LazyCache and IronPDF</h1>"
			content &= "<h2>Create CachingService</h2>"

			' Create the cache service using LazyCache
			Dim cache As IAppCache = New CachingService()

			Dim cacheKey = "uniqueKey" ' Unique key for caching the content

			' Define a factory method to generate the cacheable data
			Dim expensiveLongRunMethod As Func(Of String) = Function()
				' Render the HTML content to a PDF
				Dim pdf = renderer.RenderHtmlAsPdf(content)

				' Export the rendered PDF to a file
				pdf.SaveAs("AwesomeLazyCacheAndIronPdf.pdf")

				' Return the content as a string
				Return content
			End Function

			' Get the cached value or execute expensiveLongRunMethod to cache it
			Dim cachedValue As String = cache.GetOrAdd(cacheKey, expensiveLongRunMethod)

			' Output the cached value to the console
			Console.WriteLine(cachedValue)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

代码解释

  • 实例化渲染器:创建一个 ChromePdfRenderer 实例来处理 HTML 内容到 PDF 格式的转换。

  • Define Content: HTML content ("

    Demo LazyCache and IronPDF

    ", "

    Create CachingService

    ", etc.) is prepared. 这些内容将渲染为 PDF 并缓存以供重用。

  • 创建缓存服务:使用 LazyCache 的 CachingService 实例化一个缓存服务(IAppCache)。 该延迟缓存服务管理缓存数据的存储和检索。

  • 缓存键:分配一个唯一标识符("uniqueKey")来表示缓存的 PDF 内容。

  • 定义耗时方法:定义一个工厂方法(expensiveLongRunMethod)来生成可缓存的数据。 此方法调用 ChromePdfRenderer 将 HTML 内容渲染为 PDF。 生成的 PDF 然后保存并返回为字符串。

  • 获取或添加到缓存:调用该服务的 GetOrAdd 方法以检索与 cacheKey 关联的缓存值。 如果该值不存在于缓存中,则调用 expensiveLongRunMethod 来计算它,将其存储在缓存中并返回。 如果该值已经被缓存,则直接返回它。

  • 输出:将缓存的 PDF 内容(作为字符串)打印到控制台(Console.WriteLine(cachedValue)),展示缓存数据的检索。

输出

LazyCache C#(开发人员如何使用):图7 - 控制台输出

PDF

LazyCache C#(开发人员如何使用):图8 - PDF 输出

IronPDF 许可(提供试用)

IronPDF包需要许可证才能运行和生成PDF。 在访问包之前,在应用程序的开头添加以下代码。

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

可在 IronPDF 的试用许可页面获得试用许可。

结论

LazyCache 通过提供简单明了的 API 和自动缓存项过期,简化了 C# 应用程序中的缓存实现。 通过将 LazyCache 集成到项目中,您可以通过高效地缓存频繁访问的数据来提高性能,降低延迟,并以原子和整洁的方式优化资源利用。 无论您是在构建 Web 应用程序、APIs 还是服务,LazyCache 都可以成为提升 C# 应用程序性能和可扩展性的重要工具。

另一方面,IronPDF 作为一个强大且多功能的 C# 库,能够处理 .NET 应用程序中的 PDF 文档。 它的强大功能涵盖创建、编辑、渲染 HTML 到 PDF、以及以编程方式操作 PDF。 通过支持加密和数字签名进行安全文档处理,IronPDF 能够帮助开发人员高效管理和定制 PDF 工作流程,使其成为 C# 开发中文档管理和生成任务的宝贵工具。

常见问题解答

什么是 LazyCache,它如何使 .NET 应用程序受益?

LazyCache 是为 .NET/ASP.NET Core 应用程序设计的缓存提供程序库。它通过简化缓存实现、减少样板代码和通过内存数据存储提高性能来使这些应用程序受益,从而最小化不必要的数据检索操作。

如何在 C# 中使用 LazyCache 实现缓存?

要在 C# 中使用 LazyCache 实现缓存,您需要通过 NuGet 安装该库,并使用 LazyCache 的 CachingService 设置一个缓存服务。您可以通过使用 GetOrAdd 方法缓存数据,该方法存储方法调用的结果,并提供唯一的键和委托以在数据尚未缓存在时获取数据。

LazyCache 如何确保数据在缓存中保持最新?

LazyCache 通过支持基于可配置策略的缓存项自动过期来确保数据保持最新。此功能允许开发人员设置过期时间,确保不向用户提供过时的数据。

LazyCache 有什么使它线程安全?

LazyCache 由于其设计,是线程安全的,允许多个线程与缓存交互而不会导致数据损坏。它使用双重锁定机制来确保缓存操作在多线程应用程序中安全执行。

如何在 C# 项目中优化 PDF 文档管理?

您可以使用 IronPDF 优化 C# 项目中的 PDF 文档管理,它提供强大的功能,如从 HTML 到 PDF 的转换、内容提取和 PDF 编辑。它支持跨平台兼容性,并可以与 LazyCache 集成以缓存生成的 PDF,从而提高性能。

是否可以使用 LazyCache 进行分布式缓存?

是的,LazyCache 提供可扩展性,允许开发人员实现自定义缓存策略,包括分布式缓存。这种灵活性使其能够与其他缓存系统集成,以支持分布式环境。

将 C# PDF 库与 LazyCache 结合使用有什么好处?

将像 IronPDF 这样的 C# PDF 库与 LazyCache 结合使用,您可以高效地生成和缓存 PDF 文档。这种组合通过避免冗余的 PDF 生成提高了应用程序性能,并能快速访问频繁请求的文档。

使用像 IronPDF 这样的 C# PDF 库需要什么许可要求?

IronPDF 需要许可证才能充分利用其全部功能。开发人员可以从 IronPDF 的网站开始获得试用许可证,并须在其应用程序代码中包括许可证密钥来激活库以生成 PDFs。

LazyCache 如何提高应用程序性能?

LazyCache 通过将频繁访问的数据存储在内存中,减少了对重复数据检索操作的需求,从而提高了应用程序性能。这导致了更快的响应时间,并减少了数据库或外部数据源的负载。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。