跳過到頁腳內容
.NET幫助

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

快取(Caching)是軟體開發中的一種基本技術,可將經常存取的資料儲存在記憶體或速度較快的儲存媒體中,從而改善效能。 在 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:

在 C# 中使用 LazyCache 非常簡單直接,這要歸功於其直觀的 API。 以下是一個基本範例,示範如何使用 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# (How It Works For Developers):圖 1 - IronPDF

IronPDF 是一個功能強大的 C# PDF 函式庫,可在 .NET 專案中產生、編輯 PDF 文件,並從 PDF 文件中抽取內容。 以下是一些主要特點:

  1. HTML 轉 PDF:

    • 將 HTML、CSS 及 JavaScript 內容轉換為 PDF 格式。
    • 使用 Chrome Rendering Engine 繪製像素完美的 PDF。
    • 從 URL、HTML 檔案或 HTML 字串產生 PDF。

2.圖片和內容轉換:

  • 將圖像轉換成 PDF 或從 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 建立一個 Console 應用程式,如下所示。

LazyCache C# (How It Works For Developers):圖 2 - 控制台應用程式

提供專案名稱。

LazyCache C# (How It Works For Developers):圖 3 - 專案設定

提供 .NET 版本。

LazyCache C# (How It Works For Developers):圖 4 - 目標框架

安裝 IronPDF 套件。

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

安裝 LazyCache 套件以新增快取方法呼叫。

LazyCache C# (How It Works For Developers):圖 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)。 此 lazy 快取服務可管理快取資料的儲存與擷取。

*快取鍵:指派一個唯一識別碼("uniqueKey")來表示快取的 PDF 內容。

*定義昂貴的方法:定義了一個工廠方法(expensiveLongRunMethod)來產生可快取的資料。 此方法呼叫 ChromePdfRenderer 將 HTML 內容渲染為 PDF。 翻譯後的 PDF 將以字串形式儲存與傳回。

*取得或新增至快取:呼叫服務的 GetOrAdd 方法來檢索與 cacheKey 關聯的快取值。 如果快取中不存在該值,則呼叫 expensiveLongRunMethod 來計算該值,將其儲存在快取中,然後傳回該值。 如果數值已被快取,則會直接返回。

*輸出:快取的 PDF 內容(作為字串)列印到控制台(Console.WriteLine(cachedValue)),示範了快取資料的檢索。

輸出

LazyCache C# (How It Works For Developers):圖 7 - 控制台輸出

PDF

LazyCache C# (How It Works For Developers):圖 8 - PDF 輸出

IronPDF 授權(可試用)

IronPDF 套件需要授權才能執行和產生 PDF。 在存取套件之前,在應用程式的開頭加入下列程式碼。

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY";
Imports IronPdf

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY"
$vbLabelText   $csharpLabel

可在 IronPDF 的試用授權頁面上取得試用授權。

結論

LazyCache 透過提供直接的 API 以及緩存項目的自動過期,簡化了 C# 應用程式中的緩存實作。 透過將 LazyCache 整合到您的專案中,您可以有效地快取經常存取的資料、降低延遲,並以原子式整齊的方式最佳化資源利用率,進而提升效能。 無論您是在建立網頁應用程式、API 或服務,LazyCache 都能成為您提升 C# 應用程式效能與擴充性的重要工具。

另一方面,IronPDF 作為在 .NET 應用程式中處理 PDF 文件的功能強大且多樣化的 C# 函式庫而脫穎而出。 其強大的功能包括建立、編輯、將 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 通過將經常存取的數據儲存在記憶中,減少重複的數據檢索操作來提高應用程式效能。這導致更快的響應時間和減少對資料庫或外部數據來源的負載。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我