在整个程序中调用变量时出现问题 c#
我认为这非常简单,但我对如何设置变量“结果”感到困惑(请参阅下面的代码),因此当我希望计时器显示当前 RAM 使用情况除以总数时,我可以稍后在程序中调用它安装 RAM 以收集使用百分比。 WMI 收集已安装 RAM 的方式一直让我感到困惑,因为它必须执行结果[“TotalVisibleMemorySize”]。将整个代码块放在计时器中的问题是,它每 2 秒刷新一次,这确实会滞后计数器,因为 WMI 很慢。谢谢!
private void Form1_Load(object sender, EventArgs e)
{
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject result in results)
{
label1.Text = Convert.ToInt32(result["TotalVisibleMemorySize"]) + " KB";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Value = (int)(performanceCounter1.NextValue() - Convert.ToInt32(result["TotalVisibleMemorySize"]));
label1.Text = "Processor Time: " + progressBar1.Value.ToString() + "%";
}
I think this is very simple but I am confused on how to set the variable "result" (see the code below) so I can call it later on in the program when I want the timer to display the current RAM usage divided by the total RAM installed to gather a usage percent. The way WMI gathers the installed RAM has been throwing me off as it has to do result["TotalVisibleMemorySize"]. The issue with having the whole block of code in the timer is that it refreshes every 2 seconds which would really lag up the counter since WMI is slow. Thanks!
private void Form1_Load(object sender, EventArgs e)
{
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject result in results)
{
label1.Text = Convert.ToInt32(result["TotalVisibleMemorySize"]) + " KB";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Value = (int)(performanceCounter1.NextValue() - Convert.ToInt32(result["TotalVisibleMemorySize"]));
label1.Text = "Processor Time: " + progressBar1.Value.ToString() + "%";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您的结果变量位于 Form1_Load 方法中。
您需要将其移出该范围,或者作为 Form1 的成员,或者作为全局变量(如在 Program.cs 中)。
我建议不要执行全局变量,而是创建一个私有变量,例如:
然后当您需要时,在 Form1 类的其他地方,您可以使用
results.Whatever
Well, your results variable is in your Form1_Load method.
You'd need to move it outside that scope, either as a member of Form1, or a global (like in Program.cs.)
I'd recommend NOT doing a global, but creating a private variable like:
Then when you need to, in other places in your Form1 class you could use the
results.Whatever
您可以在类中声明私有变量:
You are allowed to declare private variable inside the class: