.NET 幫助

Dottrace .NET Core(對開發人員的作用)

Chipego
奇佩戈·卡林达
2024年7月1日
分享:

介紹 Dottrace .NET Core,這是在 .NET 生態系統中的一個強大工具,是進行性能剖析的必備 .NET 工具。 作為一個.NET性能剖析器,.NET追蹤工具使開發人員能夠捕捉詳細的追蹤文件,提供關於運行進程的運行時事件的見解。 這個工具對於優化在.NET框架上構建的應用程序是不可或缺的。

無論是進行單元測試還是整合持續集成構建,Dottrace 可讓您有效監控並分析應用程式的性能。 藉由利用這個工具,您可以更深入地理解您的應用程式行為,確保最佳效能和可靠性。

IronPDF 是一個用於在 .NET 應用程式中處理 PDF 的綜合性函式庫。 它允許您創建、編輯和提取 PDF 文件中的內容。 IronPDF 支援將 HTML 轉換為 PDF、PDF 合併和分割等功能。 這個程式庫對於需要生成或操作 PDF 文件的任何應用程式都是一個寶貴的工具。 本文將結合這個庫與Dottrace,展示Dottrace和IronPDF的實際應用效果。

開始使用Dottrace .NET Core

在 .NET 專案中設定 Dottrace .NET Core

首先,您需要使用 NuGet 安裝 Dottrace .NET Core。 打開 Visual Studio 並按照以下步驟進行:

  1. 打開 Visual Studio。

  2. 選擇建立新專案

  3. 選擇控制台應用程式 (.NET Core),然後點擊下一步

  4. 將您的專案命名為DottraceExample並點擊建立

  5. 方案總管中,右鍵點擊專案並選擇管理 NuGet 套件

  6. 在NuGet套件管理器中,搜尋JetBrains.dotTrace.CommandLineTools

  7. 選擇套件並點擊安裝

    這會將 Dottrace 安裝為您專案中的一個依賴項。

    Dottrace .NET Core(如何為開發人員工作):圖 1 - 安裝 JetBrains.dotTrace 套件

分析一個簡單的控制台應用程式

讓我們創建一個基本的控制台應用程式進行分析。將 Program.cs 中的代碼替換為以下內容:

using System;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting application...");
        Thread.Sleep(5000); // Simulating a time-consuming operation
        Console.WriteLine("Application finished.");
    }
}
using System;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting application...");
        Thread.Sleep(5000); // Simulating a time-consuming operation
        Console.WriteLine("Application finished.");
    }
}
Imports System
Imports System.Threading
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Console.WriteLine("Starting application...")
		Thread.Sleep(5000) ' Simulating a time-consuming operation
		Console.WriteLine("Application finished.")
	End Sub
End Class
$vbLabelText   $csharpLabel

按下F5來建置並執行您的應用程式。 一旦應用程式運行,您將需要其進程 ID 進行分析。 您可以透過 Visual Studio 的診斷工具視窗或檢查工作管理員來找到進程 ID。

要使用Dottrace分析您的應用程式,請打開終端視窗或Visual Studio中的套件管理器主控台並運行:

dotnet trace collect --process-id <your-process-id> --output trace.nettrace

<your-process-id> 替換為您正在運行的應用程序的實際進程 ID。

在您的應用程式完成後,您將擁有一個trace.nettrace文件。此文件包含在應用程式執行期間收集的所有分析數據。 您可以在 Visual Studio 中分析此文件。 請依照以下步驟操作:

  1. 打開 Visual Studio。

  2. 移動到 檔案 > 開啟 > 檔案

  3. 選擇trace.nettrace文件,然後點擊打開

    Visual Studio 將顯示詳細的性能數據,讓您可以識別並修復性能瓶頸。

    現在您已經設置了 Dottrace 並創建了一個基本的分析範例,您可以繼續實現更高級的功能。

實現 Dottrace .NET Core 功能

分析 CPU 使用情況

Dottrace .NET Core 的其中一個主要功能是分析 CPU 使用情況。 這有助於您確定哪些部分的代碼消耗最多的CPU資源。 以下是操作方法:

首先,在 Visual Studio 中啟動您的應用程式。 然後,在終端或套件管理員主控台中運行:

dotnet trace collect --process-id <your-process-id> --output cpu_usage.nettrace

<your-process-id> 替換為您應用程式的實際進程 ID。 一旦性能分析會話完成,請在 Visual Studio 中打開cpu_usage.nettrace文件:

using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        var sw = new Stopwatch();
        sw.Start();
        // Simulate a CPU-intensive operation
        for (int i = 0; i < 1000000000; i++) { }
        sw.Stop();
        Console.WriteLine($"Elapsed Time: {sw.ElapsedMilliseconds} ms");
    }
}
using System;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        var sw = new Stopwatch();
        sw.Start();
        // Simulate a CPU-intensive operation
        for (int i = 0; i < 1000000000; i++) { }
        sw.Stop();
        Console.WriteLine($"Elapsed Time: {sw.ElapsedMilliseconds} ms");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim sw = New Stopwatch()
		sw.Start()
		' Simulate a CPU-intensive operation
		For i As Integer = 0 To 999999999
		Next i
		sw.Stop()
		Console.WriteLine($"Elapsed Time: {sw.ElapsedMilliseconds} ms")
	End Sub
End Class
$vbLabelText   $csharpLabel

此代碼模擬了 CPU 密集型操作。 當您分析 cpu_usage.nettrace 文件時,您會看到迴圈佔用了大量的 CPU 時間。

監控記憶體分配

Dottrace .NET Core 也可以幫助您監控應用程序中的記憶體分配。 這對識別記憶體洩漏和優化記憶體使用非常重要。

運行您的應用程式並收集記憶體分配數據:

dotnet trace collect --process-id <your-process-id> --output memory_allocation.nettrace

會議結束後,在 Visual Studio 中打開 memory_allocation.nettrace 文件:

using System;
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10000; i++)
        {
            var data = new byte[1024]; // Allocate 1KB
        }
        Console.WriteLine("Memory allocation completed.");
    }
}
using System;
class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10000; i++)
        {
            var data = new byte[1024]; // Allocate 1KB
        }
        Console.WriteLine("Memory allocation completed.");
    }
}
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		For i As Integer = 0 To 9999
			Dim data = New Byte(1023){} ' Allocate 1KB
		Next i
		Console.WriteLine("Memory allocation completed.")
	End Sub
End Class
$vbLabelText   $csharpLabel

這段程式碼在迴圈中分配記憶體。分析memory_allocation.nettrace檔案將顯示分配了多少記憶體以及在程式碼中發生的位置。

分析 I/O 操作

分析 I/O 操作是另一個重要功能。 它幫助您了解讀取與寫入檔案對性能的影響。

啟動您的應用程式並收集 I/O 數據:

dotnet trace collect --process-id <your-process-id> --output io_operations.nettrace

在 Visual Studio 中開啟 io_operations.nettrace 檔案進行分析:

using System;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        var filePath = "test.txt";
        // Write to file
        using (var writer = new StreamWriter(filePath))
        {
            for (int i = 0; i < 1000; i++)
            {
                writer.WriteLine("This is a test line.");
            }
        }
        // Read from file
        using (var reader = new StreamReader(filePath))
        {
            while (reader.ReadLine() != null) { }
        }
        Console.WriteLine("I/O operations completed.");
    }
}
using System;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        var filePath = "test.txt";
        // Write to file
        using (var writer = new StreamWriter(filePath))
        {
            for (int i = 0; i < 1000; i++)
            {
                writer.WriteLine("This is a test line.");
            }
        }
        // Read from file
        using (var reader = new StreamReader(filePath))
        {
            while (reader.ReadLine() != null) { }
        }
        Console.WriteLine("I/O operations completed.");
    }
}
Imports System
Imports System.IO
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim filePath = "test.txt"
		' Write to file
		Using writer = New StreamWriter(filePath)
			For i As Integer = 0 To 999
				writer.WriteLine("This is a test line.")
			Next i
		End Using
		' Read from file
		Using reader = New StreamReader(filePath)
			Do While reader.ReadLine() IsNot Nothing
			Loop
		End Using
		Console.WriteLine("I/O operations completed.")
	End Sub
End Class
$vbLabelText   $csharpLabel

這段程式碼對檔案進行讀寫操作。分析 io_operations.nettrace 檔案將揭示在 I/O 操作上所花費的時間。

識別性能瓶頸

識別性能瓶頸是使用 Dottrace 的主要目的之一。 透過分析收集到的跟踪文件,您可以找出程式碼運行緩慢的部分。

啟動應用程式並收集效能數據:

dotnet trace collect --process-id <your-process-id> --output performance_bottlenecks.nettrace

在 Visual Studio 中開啟performance_bottlenecks.nettrace檔案:

using System;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting application...");
        // Simulate a time-consuming operation
        Thread.Sleep(5000);
        Console.WriteLine("Application finished.");
    }
}
using System;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Starting application...");
        // Simulate a time-consuming operation
        Thread.Sleep(5000);
        Console.WriteLine("Application finished.");
    }
}
Imports System
Imports System.Threading
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Console.WriteLine("Starting application...")
		' Simulate a time-consuming operation
		Thread.Sleep(5000)
		Console.WriteLine("Application finished.")
	End Sub
End Class
$vbLabelText   $csharpLabel

這段程式碼模擬應用程式中的延遲。 分析 performance_bottlenecks.nettrace 檔案將顯示最多時間花費的部分,幫助您優化這些部分。

這些範例涵蓋了 Dottrace .NET Core 的關鍵功能。 您現在可以分析 CPU 使用情況、監控記憶體分配、分析 I/O 操作、識別性能瓶頸,並在生產環境中進行分析。 每個功能都有助於優化和改善您的.NET Core應用程式。

將 Dottrace 與 IronPDF 整合

IronPDF 介紹

Dottrace .NET Core(它對開發者如何運作):圖 2 - IronPDF 網頁

IronPDF 是一個強大的 .NET 庫,可讓您在 C# 應用程式中輕鬆生成、編輯和管理 PDF。 無論您需要從頭開始創建新PDF、將HTML轉換為PDF,還是操作現有的PDF,IronPDF都提供了豐富的功能集來高效地完成這些任務。 這對於需要 PDF 生成和處理的應用程式非常有利,如報告系統、文件管理解決方案和網路應用程式。

IronPDF與Dottrace合併的使用案例

考慮一個情境,你有一個為使用者生成 PDF 報告的網絡應用程式。 透過使用 Dottrace,您可以追蹤 PDF 生成過程的性能,使用追蹤文件識別性能問題,並進行改進以提升用戶體驗。 此整合對於需要處理大量 PDF 文件或要求高效能處理的應用程式特別有價值。

使用案例的程式碼範例

以下是一個完整的程式碼範例,演示如何將IronPDF與Dottrace整合。 此範例創建了一個簡單的 HTML 到 PDF 轉換,並使用 Dottrace 監控操作的性能。

using System;
using IronPdf;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Session;
class Program
{
    static void Main(string[] args)
    {
        // Start tracing session
        using (var session = new TraceEventSession("MySession"))
        {
            session.EnableProvider("Microsoft-Windows-DotNETRuntime");
            // Perform PDF generation
            var pdfDocument = GeneratePdf("Hello, world!");
            // Save the PDF to a file
            pdfDocument.SaveAs("example.pdf");
            // Stop tracing session
            session.Stop();
        }
        Console.WriteLine("PDF generated and performance traced successfully.");
    }
    static PdfDocument GeneratePdf(string htmlContent)
    {
        // Create an instance of the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();
        // Convert HTML to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        return pdfDocument;
    }
}
using System;
using IronPdf;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Session;
class Program
{
    static void Main(string[] args)
    {
        // Start tracing session
        using (var session = new TraceEventSession("MySession"))
        {
            session.EnableProvider("Microsoft-Windows-DotNETRuntime");
            // Perform PDF generation
            var pdfDocument = GeneratePdf("Hello, world!");
            // Save the PDF to a file
            pdfDocument.SaveAs("example.pdf");
            // Stop tracing session
            session.Stop();
        }
        Console.WriteLine("PDF generated and performance traced successfully.");
    }
    static PdfDocument GeneratePdf(string htmlContent)
    {
        // Create an instance of the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();
        // Convert HTML to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        return pdfDocument;
    }
}
Imports System
Imports IronPdf
Imports Microsoft.Diagnostics.Tracing
Imports Microsoft.Diagnostics.Tracing.Session
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Start tracing session
		Using session = New TraceEventSession("MySession")
			session.EnableProvider("Microsoft-Windows-DotNETRuntime")
			' Perform PDF generation
			Dim pdfDocument = GeneratePdf("Hello, world!")
			' Save the PDF to a file
			pdfDocument.SaveAs("example.pdf")
			' Stop tracing session
			session.Stop()
		End Using
		Console.WriteLine("PDF generated and performance traced successfully.")
	End Sub
	Private Shared Function GeneratePdf(ByVal htmlContent As String) As PdfDocument
		' Create an instance of the HtmlToPdf renderer
		Dim renderer = New ChromePdfRenderer()
		' Convert HTML to PDF
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		Return pdfDocument
	End Function
End Class
$vbLabelText   $csharpLabel

Dottrace .NET Core(它對開發者的運作方式):圖 3 - 來自前面代碼示例的控制台輸出

在此範例中,我們首先使用 Dottrace 創建一個 TraceEventSession 來捕獲效能數據。 接著,我們使用 IronPDF 從簡單的 HTML 字符串生成 PDF。 在儲存 PDF 之後,我們停止追蹤會話。

Dottrace .NET Core(對於開發者來說是如何運作的):圖 4 - 先前代碼範例輸出的 PDF

這使我們能夠監控 PDF 生成過程的性能並收集其執行的寶貴洞見。

結論

探索 IronPDF 授權選項 頁面,以了解可用的授權及其各自的價格。

通過將Dottrace與IronPDF集成,您可以顯著提升PDF生成流程的性能和可靠性。 此整合提供有關應用程序如何處理 PDF 任務的寶貴見解,幫助您優化操作並確保順暢的用戶體驗。 IronPDF 提供了一整套功能來處理 PDF,使其成為任何 .NET 開發人員不可或缺的工具。

IronPDF 提供免費試用版,授權費用從 $749 起,讓您在購買前評估其功能。 結合Dottrace和IronPDF的功能可以幫助您創建滿足用戶需求的高效能、高效應用程式。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
Supersocket C# 範例(開發人員如何使用)
下一個 >
Deedle C#(如何為開發人員工作)