做课程设计时候遇到的问题,线程,timer(已通过线程解决,给大家参考)

我现在在做一个系统监视软件遇到了这样的问题
这是获取CPU状态的代码
   
   

class
{
 
public static void getCpuInfo()
        
{

            PerformanceCounter pc 
= new PerformanceCounter(CategoryName, CounterName, InstanceName);
            WNSSDataSetTableAdapters.CPUTableAdapter cpuAdapter 
= new WNSS.WNSSDataSetTableAdapters.CPUTableAdapter();
    
          
            
while (true)//保证持续运转
            {
                Thread.Sleep(
5000);
                
float cpuLoad = pc.NextValue();
                cpuAdapter.Insert(Client.testClientIP,
                    DateTime.Now,
                    cpuLoad);
     
            }

        }


}




我在MainForm中调用这个类
然后我还要继续监视系统进程

mainform中代码
 
   
   

CpuLoadInfo.getCpuInfo();
            CpuStatusLabel.Text 
=   " CPU监视:On " ;
            ProcessInfo.Run();
            ProcessStatusLabel.Text 
=   " 进程监视:On " ;



那么实际运行中呢,就出现系统一直在获取CPU状态,而无法执行到获取系统进程

然后我就思考使用System.Timers类
但是使用了之后,却发现还是有问题
   
   

private   static   void  OnTimedEvent( object  source, ElapsedEventArgs e)
        
{
            PerformanceCounter pc 
= new PerformanceCounter(CategoryName, CounterName, InstanceName);
            WNSSDataSetTableAdapters.CPUTableAdapter cpuAdapter 
= new WNSS.WNSSDataSetTableAdapters.CPUTableAdapter();
            
float cpuLoad = pc.NextValue();
                cpuAdapter.Insert(Client.testClientIP,
                    DateTime.Now,
                    cpuLoad);
   
        }




这样的话,每个timer后都会创建新的pc,监视到的数据就一直是0

现在不知道该怎么办了,大家帮帮忙啊!

解决方法:

在mainform中设置如下代码
        Thread cpuThread  =   new  Thread( new  ThreadStart(CpuLoadInfo.getCpuInfo));
         cpuThread.start();
这样我上面说的问题就轻松解决了

但是又有了新的问题,使用Thread不能传递多个参数
网上搜索了一个简单的办法,使用构造函数
下面这段是网上找的例子
http://dev.yesky.com/295/7604795.shtml
public   class  MyThread
  
{
  
public double Diameter=10;
  
public double Result=0;
  
public MyThread(int Diameter)
  
{
  
this.Diameter = Diameter;
  }

  
public void Calculate()
  
{
  Console.WriteLine( 
"Calculate Start");
  Thread.Sleep(
2000);
  Result 
= Diameter*Math.PI;;
  Console.WriteLine(
"Calculate End, Diameter is {0},Result is {1}" ,this.Diameter, Result);
  }

  }

  MyThread t
= new  MyThread( 5.0 );
  ThreadStart threadStart
= new  ThreadStart(t.Calculate)
  Thread thread
= new  Thread(threadStart);
  thread.Start();


好了,这样一个基本的多线程监控客户端基本就完成了!
可以参考我前面的cpu监视,文件监视,抓包,进程监视几篇文章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值