在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
要以響應性和有效性構建應用程序,.NET 應用程序經常需要優化方法。 緩存是一種強大的方法,包括在分散式緩存中暫時儲存經常請求的資料,以促進更快速的檢索。 透過此策略減少處理時間和伺服器負載,可以顯著提升應用程式的性能。 此外,性能計數器可以用於監控和增強緩存系統。
緩存 是在此上下文中一種強大的優化策略。 Microsoft.Extensions.Caching.Memory 為 .NET 應用程式提供了一個高效的記憶體內物件快取解決方案。 如果您在 IronPDF 中策略性地使用 MemoryCache 緩存,您的 PDF 中心應用程式將運行並響應得更快。
我們探討如何將 Microsoft.Extensions.Caching.Memory C# 示例高效地整合到 IronPDF 中。 在本文中,我們將探討有關IronPDF HTML 到 PDF 轉換流程的緩存優勢,介紹一些有用的實施技巧,並提供詳細說明以配置您在 IronPDF 程式中的緩存。 當一切塵埃落定時,您將擁有開發有效且直觀的 PDF 應用程式所需的技能和資源。
Microsoft.Extensions.Caching.Memory:.NET 中快取的基礎快取是一種用於許多高性能 .NET 應用程式的方法,將常存取的資料儲存在記憶體中以便快速檢索。 Microsoft.Extensions 是可訪問的眾多緩存選項之一。 Caching.Memory 是一個特別強大且適應性強的選擇。 此程式庫是較大範圍的Microsoft.Extensions.Caching命名空間的元件,提供了一個簡單但有效的記憶體內部快取方法。
Microsoft.Extensions.Caching.Memory」中的關鍵類型IMemoryCacheMemoryCacheIMemoryCache 的實際實現是在此類中。 它提供了緩存項目的管理和真正的內存存儲。MemoryCache 的實例。您可以使用此類別為特定的快取項目指定配置設定。 這些設定調節如下事項:
CacheEntryICacheEntryCacheEntry類別實作,提供這些功能的實用實作。Microsoft.Extensions.Caching.MemoryMicrosoft.Extensions.Caching 配置。 在應用程式啟動期間,記憶體用於在 ASP.NET Core 應用程式的服務集合中配置快取服務。 以下展示了一個已配置Microsoft.Extensions.Caching.Memory的ASP.NET Core應用程式:
首先,確保您的專案安裝了Microsoft.Extensions.Caching.Memory。 使用 NuGet 套件管理器主控台,您可以使用以下命令安裝它:
Install-Package Microsoft.Extensions.Caching.MemoryInstall-Package Microsoft.Extensions.Caching.Memory或者我們可以使用 NuGet 套件管理器來安裝該套件:

透過打開Startup.cs文件,導航至您的 ASP.NET Core 應用中的ConfigureServices方法。要設置記憶體快取服務,請新增以下代碼:
using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
// Add memory cache service
services.AddMemoryCache();
// Other service configurations...
}using Microsoft.Extensions.Caching.Memory;
public void ConfigureServices(IServiceCollection services)
{
// Add memory cache service
services.AddMemoryCache();
// Other service configurations...
}Imports Microsoft.Extensions.Caching.Memory
Public Sub ConfigureServices(ByVal services As IServiceCollection)
' Add memory cache service
services.AddMemoryCache()
' Other service configurations...
End Sub記憶體快取服務物件被添加到應用程式的服務集合並通過此代碼進行配置。 使用 AddMemoryCache 函數通過其默認配置註冊記憶體快取系統服務。
IMemoryCache一旦緩存存儲設置完成,任何需要緩存的類或組件都可以將IMemoryCache介面注入其中。 在控制器或服務類中,例如:
public class MyService
{
private readonly IMemoryCache _cache;
public MyService(IMemoryCache cache)
{
_cache = cache;
}
// Use _cache to perform caching operations...
}public class MyService
{
private readonly IMemoryCache _cache;
public MyService(IMemoryCache cache)
{
_cache = cache;
}
// Use _cache to perform caching operations...
}Public Class MyService
Private ReadOnly _cache As IMemoryCache
Public Sub New(ByVal cache As IMemoryCache)
_cache = cache
End Sub
' Use _cache to perform caching operations...
End ClassIMemoryCache 介面提供了用於從記憶體快取和檢索資料的方法。
通過設置緩存參數,您可以改變記憶體緩存的行為。 這涉及配置一組參數的方法,包括大小限制、緩存條目驅逐策略和緩存值到期規則。 這是一個如何設置快取選項的例子:
public void ConfigureServices(IServiceCollection services)
{
// Configure cache options
services.AddMemoryCache(options =>
{
options.SizeLimit = 1024; // Set the maximum size limit for the cache
options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
});
// Other service configurations...
}public void ConfigureServices(IServiceCollection services)
{
// Configure cache options
services.AddMemoryCache(options =>
{
options.SizeLimit = 1024; // Set the maximum size limit for the cache
options.CompactionPercentage = 0.75; // Set the percentage of memory to free up when the cache size exceeds the limit
options.ExpirationScanFrequency = TimeSpan.FromMinutes(5); // Set how often the cache should scan for expired items
});
// Other service configurations...
}Public Sub ConfigureServices(ByVal services As IServiceCollection)
' Configure cache options
services.AddMemoryCache(Sub(options)
options.SizeLimit = 1024 ' Set the maximum size limit for the cache
options.CompactionPercentage = 0.75 ' Set the percentage of memory to free up when the cache size exceeds the limit
options.ExpirationScanFrequency = TimeSpan.FromMinutes(5) ' Set how often the cache should scan for expired items
End Sub)
' Other service configurations...
End Sub根據您的應用程式規格修改設定。
這些指示將幫助您配置Microsoft.Extensions。 在您的 ASP.NET Core 應用程式中,使用 Caching.Memory。 應用程式因此可以更快速且更高效地運行,透過在記憶體快取中儲存和檢索經常存取的資料。
借助知名的 .NET 函式庫 IronPDF,程式設計師可以在 .NET 應用程式中生成、編輯和顯示 PDF 文件。 從 HTML 內容、照片或原始數據創建 PDF 只是它為處理 PDF 提供的眾多功能之一。 其他功能包括向現有的 PDF 文件添加文字、圖像和形狀,將 HTML 頁面轉換為 PDF,以及從 PDF 中提取文字和圖像。
以下是 IronPDF 的一些功能:
在您的專案中,確保已安裝 IronPDF 套件。 可以使用 NuGet 套件管理員主控台來安裝它:
Install-Package IronPdf
要存取ConfigureServices函數,請在您的ASP.NET Core應用程式中打開Startup.cs檔案。 要配置 IronPDF,請添加以下代碼。
using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
// Configure IronPDF
services.AddSingleton<HtmlToPdf>();
// Other service configurations...
}using IronPdf;
public void ConfigureServices(IServiceCollection services)
{
// Configure IronPDF
services.AddSingleton<HtmlToPdf>();
// Other service configurations...
}Imports IronPdf
Public Sub ConfigureServices(ByVal services As IServiceCollection)
' Configure IronPDF
services.AddSingleton(Of HtmlToPdf)()
' Other service configurations...
End Sub透過將 IronPDF 的 HtmlToPdf 服務配置為單例,此程式碼確保應用程式只建立並使用一個 HtmlToPdf 實例。
Microsoft.Extensions.Caching.Memory 與 IronPDF 結合使用在 .NET 應用程式中,Microsoft.Extensions.Caching.Memory 提供了一種存儲頻繁請求數據以加快檢索速度的實用方法。
以下是此原始碼和程式碼片段的基本使用方法說明:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
[ApiController]
[Route("[controller]")]
public class DemoController : ControllerBase
{
private readonly IMemoryCache _cache;
private readonly HtmlToPdf _htmlToPdf;
private readonly ILogger<DemoController > _logger;
public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
{
_logger = logger;
_cache = cache;
_htmlToPdf = htmlToPdf;
}
[HttpGet]
public FileContentResult Generate()
{
string fileName = "Sample.pdf";
var stream = GeneratePdf("Hello IronPDF");
return new FileContentResult(stream, "application/octet-stream")
{
FileDownloadName = fileName
};
}
private byte[] GeneratePdf(string htmlContent)
{
// object key
string cacheKey = "GeneratedPdf";
if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
{
// PDF not found in cache, generate it
var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
pdfBytes = pdfDocument.BinaryData;
// Cache the generated PDF with a sliding expiration of 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
}
return pdfBytes;
}
}
}using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using System.Net.Http.Headers;
namespace DemoWebApplication.Controllers
{
[ApiController]
[Route("[controller]")]
public class DemoController : ControllerBase
{
private readonly IMemoryCache _cache;
private readonly HtmlToPdf _htmlToPdf;
private readonly ILogger<DemoController > _logger;
public DemoController(ILogger<DemoController > logger, IMemoryCache cache, HtmlToPdf htmlToPdf)
{
_logger = logger;
_cache = cache;
_htmlToPdf = htmlToPdf;
}
[HttpGet]
public FileContentResult Generate()
{
string fileName = "Sample.pdf";
var stream = GeneratePdf("Hello IronPDF");
return new FileContentResult(stream, "application/octet-stream")
{
FileDownloadName = fileName
};
}
private byte[] GeneratePdf(string htmlContent)
{
// object key
string cacheKey = "GeneratedPdf";
if (!_cache.TryGetValue(cacheKey, out byte[] pdfBytes))
{
// PDF not found in cache, generate it
var pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent);
pdfBytes = pdfDocument.BinaryData;
// Cache the generated PDF with a sliding expiration of 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1));
}
return pdfBytes;
}
}
}Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.Extensions.Caching.Memory
Imports System.Net
Imports System.Net.Http.Headers
Namespace DemoWebApplication.Controllers
<ApiController>
<Route("[controller]")>
Public Class DemoController
Inherits ControllerBase
Private ReadOnly _cache As IMemoryCache
Private ReadOnly _htmlToPdf As HtmlToPdf
Private ReadOnly _logger As ILogger(Of DemoController )
Public Sub New(ByVal logger As ILogger(Of DemoController ), ByVal cache As IMemoryCache, ByVal htmlToPdf As HtmlToPdf)
_logger = logger
_cache = cache
_htmlToPdf = htmlToPdf
End Sub
<HttpGet>
Public Function Generate() As FileContentResult
Dim fileName As String = "Sample.pdf"
Dim stream = GeneratePdf("Hello IronPDF")
Return New FileContentResult(stream, "application/octet-stream") With {.FileDownloadName = fileName}
End Function
Private Function GeneratePdf(ByVal htmlContent As String) As Byte()
' object key
Dim cacheKey As String = "GeneratedPdf"
Dim pdfBytes() As Byte
If Not _cache.TryGetValue(cacheKey, pdfBytes) Then
' PDF not found in cache, generate it
Dim pdfDocument = _htmlToPdf.RenderHtmlAsPdf(htmlContent)
pdfBytes = pdfDocument.BinaryData
' Cache the generated PDF with a sliding expiration of 1 hour
_cache.Set(cacheKey, pdfBytes, TimeSpan.FromHours(1))
End If
Return pdfBytes
End Function
End Class
End Namespace我們導入與 Microsoft 和 ASP.NET Microsoft.Extensions.Caching.Memory 工作所需的命名空間。 我們創建了 DemoController 控制器,該控制器衍生自 ControllerBase。 此控制器將回應透過 HTTP 發送的查詢。IMemoryCache 的實例被注入到了控制器的構造函數中。
為了控制服務的生命週期,包括記憶體快取,ASP.NET Core 提供了相依性注入。 應用 [HttpGet] 屬性後,Generate 方法標記為處理指定路由 (/Demo) 發送至商店的 HTTP GET 請求。 我們嘗試通過使用給定的快取鍵從 Generate 函數內的快取中獲取天氣預報數據。 如果無法使用的數據在緩存中,我們使用Generate函數創建新的天氣數據。
在多個應用伺服器的場景中,請確保配置分散式快取以在所有伺服器中一致地處理快取。
要使用 Microsoft.Extensions.Caching.Memory,請參考提供的文件和範例程式碼,以便在 ASP.NET Core 應用程式中快取資料並提升效能。 在實際應用中,您可以調整過期策略、快取鍵以及快取行為以符合您的應用程式需求。 快取生成成本高或常被多個執行緒存取的資料,可以改善整體用戶體驗並顯著減少回應時間。

總體來說,Microsoft.Extensions.Caching.Memory 可以用來增強 .NET 應用程式的擴展性和效能,尤其是基於 ASP.NET Core 框架的應用程式。 開發人員可以透過使用內存快取來提升用戶體驗、最小化延遲和優化數據訪問。 該庫提供了一個靈活且使用者友好的 API,適用於開發針對特定應用程式需求的緩存策略,無論是緩存參考資料、查詢結果或計算值。 通過採用快取最佳實踐並將Microsoft.Extensions.Caching.Memory添加到您的.NET應用程式中,您可以實現顯著的速度提升和應用程式響應能力增強。
通過利用Microsoft.Extensions的功能,並借助IronPDF進行動態PDF創建以及Caching.Memory進行有效的數據緩存,.NET開發人員可以極大地提高應用程序的速度。這種強大的組合使開發人員能夠輕鬆設計高性能、可擴展且響應迅速的應用程序,藉此減輕服務器負載、改善用戶體驗並消除處理開銷。
IronPDF 可以以合理的價格購買,並且購買套件包括終身許可。 此套件提供卓越的價值,自$749起售,單一費用適用於多個系統。 對於持有許可證的用戶,它提供全天候的在線工程幫助。 如需了解有關收費的更多詳情,請訪問IronPDF 授權頁面。 請造訪此Iron Software相關頁面,以了解更多由Iron Software製作的產品。