C#根据当前进程,画图,并且展示进程消耗情况,进程数为4,存储在queue队列中,请给出具体代码
时间: 2024-11-15 12:26:12 浏览: 12
在C#中,你可以使用Windows Forms和System.Diagnostics命名空间来监控进程并实时绘制图形。这里是一个简单的示例,它会创建一个窗体,显示四个进程的CPU使用率,使用Queue存储进程信息:
```csharp
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;
public partial class MainForm : Form
{
private List<double> cpuUsage = new List<double>();
private Queue<ProcessInfo> processQueue = new Queue<ProcessInfo>();
private Chart chart1;
public MainForm()
{
InitializeComponent();
chart1 = new Chart();
chart1.ChartAreas.Add(new ChartArea());
this.Controls.Add(chart1);
}
private void UpdateChart()
{
while (processQueue.Count > 0)
{
ProcessInfo pInfo = processQueue.Dequeue();
double cpuPercent = pInfo.CpuPercentage;
cpuUsage.Add(cpuPercent);
cpuUsage.RemoveAt(0); // Remove oldest data if queue is full
Series series = chart1.Series["Series1"];
series.Points.AddXY(pInfo.ProcessName, cpuPercent);
// Update UI
chart1.Invalidate();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// Get processes from the system
foreach (Process p in Process.GetProcesses())
{
// Assuming ProcessInfo is a custom class with properties like ProcessName and CpuPercentage
ProcessInfo pInfo = new ProcessInfo { ProcessName = p.ProcessName, CpuPercentage = p.TotalProcessorTime.TotalMilliseconds / p.Id };
processQueue.Enqueue(pInfo);
// Limit to 4 processes for simplicity
if (processQueue.Count >= 4) break;
}
// Update chart every tick
UpdateChart();
}
public class ProcessInfo
{
public string ProcessName { get; set; }
public double CpuPercentage { get; set; }
}
}
// In your form constructor or somewhere else, start the timer
MainForm mainForm = new MainForm();
mainForm.timer1.Interval = 1000; // 1 second interval
mainForm.timer1.Start();
// Make sure you have a button or some trigger to add new processes manually, if needed
private void addButton_Click(object sender, EventArgs e)
{
ProcessInfo pInfo = // Create ProcessInfo object manually
mainForm.processQueue.Enqueue(pInfo);
}
```
这个例子假设`ProcessInfo`类存在并且包含`ProcessName`和`CpuPercentage`属性。`timer1_Tick`事件会在每秒触发一次,获取系统中的进程并将它们添加到队列中。同时,更新图表以显示每个进程的CPU使用情况。
注意:实际应用中,你需要处理线程同步和异常处理等问题。
阅读全文