---
description: >-
  This feature provides developers with real-time performance and memory usage
  data, including CPU usage, process count, thread count, handle count, memory
  metrics and performance, etc.
---

# Performance and Memory Metrics

## Overview

The Performance & Memory Metrics feature of the SiticoneSystemInfo control exposes various public properties that deliver critical system performance data. Metrics such as CPU usage, process count, thread count, committed memory, and cached memory are gathered using standard WMI queries and performance counters. These data points are essential for building applications focused on system diagnostics, monitoring, and performance optimization in .NET WinForms.

***

### Key Points

<table><thead><tr><th width="190">Aspect</th><th>Details</th></tr></thead><tbody><tr><td>Exposed Properties</td><td>CpuUsage, ProcessCount, ThreadCount, HandleCount, CommittedMemory, CachedMemory</td></tr><tr><td>Data Collection</td><td>Utilizes WMI queries and performance counters to obtain metrics related to CPU, memory, and overall system performance</td></tr><tr><td>Real-Time Updates</td><td>Metrics are refreshed asynchronously to ensure that the latest performance data is available without impacting UI responsiveness</td></tr><tr><td>Data Binding</td><td>Metrics are exposed as simple read-only properties that can be easily bound to UI elements such as labels, charts, or data grids for visualization</td></tr></tbody></table>

***

### Best Practices

<table><thead><tr><th width="251">Practice</th><th>Description</th></tr></thead><tbody><tr><td>Use asynchronous refresh</td><td>Call the asynchronous RefreshAsync() method to update performance metrics without blocking the UI thread.</td></tr><tr><td>Bind to UI components</td><td>Bind properties like CpuUsage or ProcessCount directly to UI labels or charts for dynamic display of system performance.</td></tr><tr><td>Aggregate data carefully</td><td>When displaying performance data, consider averaging or smoothing out rapid changes to prevent erratic UI behavior.</td></tr><tr><td>Validate performance data</td><td>Always check for valid data (non-zero values or reasonable ranges) to ensure that performance metrics are accurately reported.</td></tr></tbody></table>

***

### Common Pitfalls

| Pitfall                          | Description                                                                                                             | Recommendation                                                                                                      |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Inaccurate metrics on first call | Performance counters may require an initial call to initialize, leading to inaccurate readings if accessed immediately. | Always allow for an initial sample delay (e.g., using a sleep period) before retrieving the final performance data. |
| Blocking the UI thread           | Synchronous retrieval of performance metrics can freeze the UI.                                                         | Utilize asynchronous methods (e.g., RefreshAsync) to ensure the UI remains responsive during data updates.          |
| Data spikes and fluctuations     | Raw performance data may have sudden spikes, causing abrupt changes in the UI.                                          | Implement data smoothing or averaging techniques before displaying metrics on the user interface.                   |
| Limited counter availability     | Some performance counters might not be available on all systems, leading to exceptions or missing data.                 | Include proper exception handling and fallbacks when a performance counter is not available or returns an error.    |

***

### Usage Scenarios

<table><thead><tr><th width="309">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Real-Time Performance Dashboard</td><td>Display current CPU usage, process count, and memory usage on a dashboard for system monitoring.</td></tr><tr><td>Resource Monitoring Tool</td><td>Monitor system memory and handle counts in real-time to diagnose performance bottlenecks.</td></tr><tr><td>System Diagnostics Application</td><td>Log performance metrics over time for post-analysis in system diagnostics and troubleshooting.</td></tr></tbody></table>

***

### Real Life Usage Scenarios

<table><thead><tr><th width="260">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>IT Operations Monitoring</td><td>Integrate the metrics into a centralized dashboard that IT administrators use to monitor system performance across multiple workstations.</td></tr><tr><td>Performance Trend Analysis</td><td>Collect performance data over time to identify trends and predict potential system failures before they occur.</td></tr><tr><td>Resource Optimization</td><td>Use real-time metrics to adjust system resources dynamically, such as scaling services or allocating memory based on current load.</td></tr></tbody></table>

***

### Troubleshooting Tips

<table><thead><tr><th width="237">Tip</th><th>Description</th><th>Recommendation</th></tr></thead><tbody><tr><td>Allow for initialization delays</td><td>Performance counters require an initial call to establish a baseline.</td><td>Introduce a short delay (e.g., 1000 ms) before taking a second reading to ensure accurate metric values.</td></tr><tr><td>Monitor for out-of-range values</td><td>Occasionally, performance metrics may return extreme values due to transient system load.</td><td>Validate and, if necessary, smooth the data before updating the UI to avoid erratic behavior.</td></tr><tr><td>Handle exceptions gracefully</td><td>Some performance counters might not be supported on all systems.</td><td>Use try-catch blocks around performance counter initialization and reading to prevent the application from crashing.</td></tr><tr><td>Verify system capabilities</td><td>Not all systems have the same hardware support for performance counters.</td><td>Check the availability of each counter before relying on its data, and provide alternate logic if a counter is unavailable.</td></tr></tbody></table>

***

### Code Examples & Integration Demos

#### Example 1: Displaying Real-Time CPU and Memory Usage

**Description:** Bind performance metrics such as CPU usage and committed memory to UI labels for real-time display.

```csharp
// In your Form_Load event or initialization method
private async void MainForm_Load(object sender, EventArgs e)
{
    // Refresh performance metrics asynchronously
    await systemInfoControl.RefreshAsync();

    // Bind CPU usage and committed memory to UI labels
    lblCpuUsage.Text = $"CPU Usage: {systemInfoControl.CpuUsage}%";
    lblCommittedMemory.Text = $"Committed Memory: {systemInfoControl.CommittedMemory / (1024.0 * 1024):F2} MB";
}
```

#### Example 2: Updating a Chart with Process and Thread Counts

**Description:** Update a chart periodically to show the number of processes and threads.

```csharp
// Timer event for updating the chart every 5 seconds
private async void timer_Tick(object sender, EventArgs e)
{
    await systemInfoControl.RefreshAsync();
    chartPerformance.Series["Processes"].Points.AddY(systemInfoControl.ProcessCount);
    chartPerformance.Series["Threads"].Points.AddY(systemInfoControl.ThreadCount);
}
```

#### Example 3: Logging Memory Metrics for Diagnostics

**Description:** Log the committed and cached memory values to a text file for later analysis.

```csharp
private async void btnLogMetrics_Click(object sender, EventArgs e)
{
    await systemInfoControl.RefreshAsync();
    string logEntry = $"Time: {DateTime.Now}, Committed Memory: {systemInfoControl.CommittedMemory}, Cached Memory: {systemInfoControl.CachedMemory}";
    System.IO.File.AppendAllText("C:\\Temp\\PerformanceLog.txt", logEntry + Environment.NewLine);
    MessageBox.Show("Metrics logged successfully.");
}
```

***

### Review

<table><thead><tr><th width="218">Aspect</th><th>Review Comments</th></tr></thead><tbody><tr><td>Integration Simplicity</td><td>Provides straightforward read-only properties that can be easily bound to UI elements, simplifying the integration of performance metrics into applications.</td></tr><tr><td>Robustness</td><td>Utilizes standard WMI queries and performance counters for data collection; however, initial delays and exception handling are crucial for accurate reporting.</td></tr><tr><td>UI Flexibility</td><td>The control’s properties are well-suited for dynamic displays, such as labels, charts, and data grids, offering extensive flexibility for various UI layouts.</td></tr><tr><td>Documentation Clarity</td><td>Detailed examples and clear division into key points, best practices, and troubleshooting tips ensure that developers can quickly integrate and utilize this feature.</td></tr></tbody></table>

***

### Summary

Implementing the Performance & Memory Metrics feature allows you to integrate real-time system performance data into your WinForms applications. By following best practices such as using asynchronous refresh methods, binding directly to UI components, and incorporating proper error handling, you can create a responsive monitoring dashboard or diagnostics tool. Use the sample code provided as a foundation, and adjust the data smoothing or logging techniques based on your application’s requirements. Happy coding!
