跳至頁尾內容
開發者更新

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:

由於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 Rendering Engine生成像素完美的PDF。
    • 從 URL、HTML 檔案或 HTML 字串生成 PDF。
  2. 影像和內容轉換:

    • 將影像轉換為和從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的IAppCache)。 這個懶載入快取服務管理快取資料的儲存和檢索。

  • 快取鍵:指定一個唯一的識別符號("uniqueKey")來表示快取的PDF內容。

  • 定義耗時方法: 定義一個工廠方法(expensiveLongRunMethod)來生成可快取的資料。 此方法調用ChromePdfRenderer將HTML內容渲染為PDF。 生成的PDF然後被儲存並以字串形式返回。

  • 取得或新增至快取:呼叫服務的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";
Imports IronPdf

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

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

結論

LazyCache通過提供直接的API和自動過期來簡化了C#應用中的快取實作。 通過將LazyCache整合到您的專案中,您可以通過有效快取經常存取的資料來提高效能,降低延遲並在原子且有序的方式優化資源利用。 無論您是在構建網路應用程式、API還是服務,LazyCache都可以成為提高C#應用程式效能和擴展性的有價值工具。

另一方面,IronPDF在.NET應用中作為強大且多功能的C#程式庫,處理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 提供可擴展性,允許開發者實作自訂快取策略,包括分佈式快取。這種靈活性支持與其他快取系統的整合,以支持分佈式環境。

using 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核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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