跳過到頁腳內容
.NET幫助

LazyCache C#(對開發者如何理解的工作)

緩存是軟體開發中一種基本技術,用於通過將經常訪問的數據存儲在記憶體或更快的存儲介質中來提高性能。 在C#中,LazyCache是一個流行的庫,簡化了線程安全的緩存實現,使開發者能夠更輕鬆地在他們的應用程序中利用緩存,適用於重負載場景。

什麼是LazyCache?

LazyCache是.NET/ASP.NET Core應用程序的底層緩存提供程序庫,提供了一個簡單且直觀的API來緩存數據。 它以NuGet包的形式提供,可以輕鬆集成到C#項目中。 LazyCache的主要目標是簡化緩存實現,減少管理緩存信息所需的樣板代碼,使用雙鎖定緩存模式。

LazyCache的主要功能:

  1. 簡單的API: LazyCache提供了一個簡單明了的API,用於添加、檢索和刪除緩存項目。 開發者可以快速地將緩存集成到他們的應用程序或網絡服務調用中,而不需要處理複雜的緩存機制。

  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。
    • 從網址、HTML 文件或 HTML 字串生成 PDF。
  2. 圖像和內容轉換

    • 將圖像轉換為PDF,或從PDF中提取圖像。
    • 從現有PDF中提取文本和圖像。
    • 支持多種圖像格式。
  3. 編輯和操縱

    • 為PDF設置屬性、安全性和權限。
    • 添加數字簽名。
    • 兼容 .NET Core(8、7、6、5 和 3.1+)、.NET Standard(2.0+)和 .NET Framework(4.6.2+)。
  4. 跨平台支持

    • 兼容 Windows、Linux 和 macOS。
    • 可在 NuGet 上獲得,便於安裝。

使用 IronPDF 和 DuckDB .NET 生成 PDF 文檔

使用IronPDF和LazyCache生成PDF文檔

DuckDB C#(開發人員如何使用):圖 3 - 控制台應用程序

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集成到您的項目中,您可以通過高效緩存經常訪問的數據來提高性能,減少延遲並在原子而整潔的方式中優化資源利用率。 無論您是在構建網絡應用程序、API還是服務,LazyCache都是提高您的C#應用程序性能和可擴展性的寶貴工具。

另一方面,IronPDF作為一個強大而多才的C#庫,在.NET應用程序中處理PDF文檔中脫穎而出。 其強大的功能涵蓋了創建、編輯、將HTML渲染為PDF以及程序化操作PDF。 通過加密和數字簽名來安全處理文檔的功能,IronPDF使開發人員能夠有效地管理和自定義PDF工作流程,使其成為C#開發中廣泛使用的文檔管理和生成任務的寶貴工具。

常見問題解答

什麼是 LazyCache,它對 .NET 應用程式有何好處?

LazyCache 是專為 .NET/ASP.NET Core 應用程式設計的快取提供程式庫。它透過簡化快取的實作、減少樣板代碼,以及通過記憶內儲存增強效能來為這些應用程式帶來好處,從而減少不必要的數據檢索操作。

如何使用 LazyCache 在 C# 中實作快取?

要在 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 網站開始試用許可證,並必須在其應用程式代碼中包含許可證金鑰以啟用庫來生成 PDF。

LazyCache 如何提高應用程式效能?

LazyCache 通過將經常存取的數據儲存在記憶中,減少重複的數據檢索操作來提高應用程式效能。這導致更快的響應時間和減少對資料庫或外部數據來源的負載。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。