C#定义问题
我在代码中将性能计数器定义为:
PerformanceCounterCategory pcc = new PerformanceCounterCategory("Network Interface", ipAddress);
string instance = pcc.GetInstanceNames()[1]; //first card
PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", instance, ipAddress);
,但我想将其定义为全局并在不同的函数中使用,因此我将代码更改为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Management;
namespace networkPerformans
{
class Searcher
{
ConnectionClassOleDb cc = new ConnectionClassOleDb();
int threadNo, range, step, modJobs;
frmIpTarama frm;
ArrayList tmpList = new ArrayList();
DateTime endTime, startTime;
ListViewItem x;
long pingSuresi;
string machineName;
double utilization;
public Searcher(int threadNo, frmIpTarama frm)
{
this.threadNo = threadNo;
this.frm = frm;
}
public void getIpRange()
{
frm.calcIpAddressRange();
if (frm.calcIpAddressRange())
{
range = frm.intEndIp - frm.intStartIp + 1; // 13 - 1 = 12 + 1 = 13
step = range / (int)frm.nudThreads.Value; // 13 / 5 = 2
modJobs = (range % frm.threadSayac); // 13 mod 5 kalan= 3+
frm.lblGorev.Text = range.ToString();
if (threadNo <= modJobs)
{
step++;
}
int i = 0;
int currentIp;
while (i < step)
{
currentIp = (threadNo) + (frm.threadSayac * i) + frm.intStartIp;
string ipAddress = new IPAddress(BitConverter.GetBytes(IPAddress.NetworkToHostOrder(currentIp))).ToString();
if (currentIp <= frm.intEndIp)
{
getperformance(ipAddress, threadNo);
}
else
{
break;
}
i++;
}
}
}
public string pingStatus(string ip)
{
Ping p = new Ping();
PingReply reply = p.Send(ip);
pingSuresi = reply.RoundtripTime;
return reply.Status.ToString();
}
public void getperformance(string ipAddress, int threadNo)
{
string pingDurumu = pingStatus(ipAddress);
bool veriGoster = frm.cbVerileriGosterme.Checked;
if (pingDurumu == IPStatus.Success.ToString())
{
if (!veriGoster)
{
x = frm.lvAddresses.Items.Add(ipAddress);
x.SubItems.AddRange(new String[] { "", "", "", "", "", "", "", "", "" });
}
try
{
startTime = DateTime.Now;
PerformanceCounterCategory pcc = new PerformanceCounterCategory("Network Interface", ipAddress);
string instance = pcc.GetInstanceNames()[1]; // 1. network kartı
PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", instance, ipAddress);
PerformanceCounter pcReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance, ipAddress);
PerformanceCounter pcSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance, ipAddress);
PerformanceCounter pcProcessorTime = new PerformanceCounter("Processor", "% Processor Time", "_Total", ipAddress);
PerformanceCounter pcKullanilabilirRam = new PerformanceCounter("Memory", "Available MBytes", "", ipAddress);
const int numberOfIterations = 10;
float receiveSum = 0;
float sendSum = 0;
float cpuSum = 0;
float bandwidth = bandwidthCounter.NextValue();
for (int index = 0; index < numberOfIterations; index++)
{
sendSum += pcSent.NextValue();
receiveSum += pcReceived.NextValue();
cpuSum += pcProcessorTime.NextValue();
}
float dataSent = sendSum;
float dataReceived = receiveSum;
//MessageBox.Show(dataSent.ToString() +" "+ dataReceived.ToString());
if ((dataSent != 0) && (dataReceived != 0))
{
utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
}
else
{
string instance2 = pcc.GetInstanceNames()[0];
PerformanceCounter bandwidthCounter2 = new PerformanceCounter("Network Interface", "Current Bandwidth", instance2, ipAddress);
PerformanceCounter pcReceived2 = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance2, ipAddress);
PerformanceCounter pcSent2 = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance2, ipAddress);
float bandwidth2 = bandwidthCounter2.NextValue();
for (int index = 0; index < numberOfIterations; index++)
{
sendSum += pcSent2.NextValue();
receiveSum += pcReceived2.NextValue();
cpuSum += pcProcessorTime.NextValue();
}
float dataSent2 = sendSum;
float dataReceived2 = receiveSum;
utilization = (8 * (dataSent2 + dataReceived2)) / (bandwidth2 * numberOfIterations) * 100;
}
cpuSum = cpuSum / numberOfIterations;
IPHostEntry host = new IPHostEntry();
host = Dns.GetHostEntry(ipAddress);//ip Address is to be specified here
machineName = host.HostName;
endTime = DateTime.Now;
if (!frm.cbVerileriGosterme.Checked)
{
x.SubItems[1].Text = machineName;
x.SubItems[2].Text = threadNo.ToString();
x.SubItems[3].Text = pingDurumu;
x.SubItems[4].Text = pingSuresi.ToString();
x.SubItems[5].Text = (endTime - startTime).TotalSeconds.ToString();
x.SubItems[6].Text = utilization.ToString();
x.SubItems[7].Text = cpuSum.ToString();
x.SubItems[8].Text = pcKullanilabilirRam.NextValue().ToString();
x.SubItems[9].Text = "";
}
cc.sorgu = " EXECUTE [dbo].[prVeriKaydet] "
+ "'" + frm.taramaNo + "',"
+ "'" + ipAddress + "',"
+ "'" + machineName + "',"
+ pingSuresi.ToString().Replace(",", ".") + ","
+ (endTime - startTime).TotalSeconds.ToString().Replace(",", ".") + ","
+ utilization.ToString().Replace(",", ".") + ","
+ cpuSum.ToString().Replace(",", ".") + ","
+ pcKullanilabilirRam.NextValue().ToString().Replace(",", ".");
cc.Run(cc.sorgu, "");
}
catch (Exception ex)
{
endTime = DateTime.Now;
if (!veriGoster)
{
x.SubItems[2].Text = threadNo.ToString();
x.SubItems[3].Text = pingDurumu;
x.SubItems[4].Text = pingSuresi.ToString();
x.SubItems[5].Text = (endTime - startTime).TotalSeconds.ToString();
x.SubItems[5].Text = "0";
x.SubItems[6].Text = "0";
x.SubItems[7].Text = "0";
x.SubItems[8].Text = "0";
x.SubItems[9].Text = ex.Message;
}
}
}
lock (frm.progressBar1)
{
frm.progressBar1.Value++;
frm.lblIs.Text = frm.progressBar1.Value.ToString();
if (range - frm.nudThreads.Value < frm.progressBar1.Value)
{
frm.threadSayacKontrol--;
}
frm.tbThreadSayisi.Text = frm.threadSayacKontrol.ToString();
if (frm.progressBar1.Value == frm.progressBar1.Maximum)
{
frm.progressBar1.Value = 0;
frm.btnTara.Enabled = true;
frm.TheColumnSorter.CurrentColumn = 0;
frm.btnDurdurDevam.Enabled = false;
if (frm.cbSurekliTara.Checked)
{
frm.tara();
}
}
}
}
}
}
然后当我使用 bandwidthCounter
时,出现此错误:
对象引用未设置为 对象的实例。
缺什么?
I have defined a performance counter as:
PerformanceCounterCategory pcc = new PerformanceCounterCategory("Network Interface", ipAddress);
string instance = pcc.GetInstanceNames()[1]; //first card
PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", instance, ipAddress);
in my code, but I want to define it global and use in different functions, so I changed the code to:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Management;
namespace networkPerformans
{
class Searcher
{
ConnectionClassOleDb cc = new ConnectionClassOleDb();
int threadNo, range, step, modJobs;
frmIpTarama frm;
ArrayList tmpList = new ArrayList();
DateTime endTime, startTime;
ListViewItem x;
long pingSuresi;
string machineName;
double utilization;
public Searcher(int threadNo, frmIpTarama frm)
{
this.threadNo = threadNo;
this.frm = frm;
}
public void getIpRange()
{
frm.calcIpAddressRange();
if (frm.calcIpAddressRange())
{
range = frm.intEndIp - frm.intStartIp + 1; // 13 - 1 = 12 + 1 = 13
step = range / (int)frm.nudThreads.Value; // 13 / 5 = 2
modJobs = (range % frm.threadSayac); // 13 mod 5 kalan= 3+
frm.lblGorev.Text = range.ToString();
if (threadNo <= modJobs)
{
step++;
}
int i = 0;
int currentIp;
while (i < step)
{
currentIp = (threadNo) + (frm.threadSayac * i) + frm.intStartIp;
string ipAddress = new IPAddress(BitConverter.GetBytes(IPAddress.NetworkToHostOrder(currentIp))).ToString();
if (currentIp <= frm.intEndIp)
{
getperformance(ipAddress, threadNo);
}
else
{
break;
}
i++;
}
}
}
public string pingStatus(string ip)
{
Ping p = new Ping();
PingReply reply = p.Send(ip);
pingSuresi = reply.RoundtripTime;
return reply.Status.ToString();
}
public void getperformance(string ipAddress, int threadNo)
{
string pingDurumu = pingStatus(ipAddress);
bool veriGoster = frm.cbVerileriGosterme.Checked;
if (pingDurumu == IPStatus.Success.ToString())
{
if (!veriGoster)
{
x = frm.lvAddresses.Items.Add(ipAddress);
x.SubItems.AddRange(new String[] { "", "", "", "", "", "", "", "", "" });
}
try
{
startTime = DateTime.Now;
PerformanceCounterCategory pcc = new PerformanceCounterCategory("Network Interface", ipAddress);
string instance = pcc.GetInstanceNames()[1]; // 1. network kartı
PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", instance, ipAddress);
PerformanceCounter pcReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance, ipAddress);
PerformanceCounter pcSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance, ipAddress);
PerformanceCounter pcProcessorTime = new PerformanceCounter("Processor", "% Processor Time", "_Total", ipAddress);
PerformanceCounter pcKullanilabilirRam = new PerformanceCounter("Memory", "Available MBytes", "", ipAddress);
const int numberOfIterations = 10;
float receiveSum = 0;
float sendSum = 0;
float cpuSum = 0;
float bandwidth = bandwidthCounter.NextValue();
for (int index = 0; index < numberOfIterations; index++)
{
sendSum += pcSent.NextValue();
receiveSum += pcReceived.NextValue();
cpuSum += pcProcessorTime.NextValue();
}
float dataSent = sendSum;
float dataReceived = receiveSum;
//MessageBox.Show(dataSent.ToString() +" "+ dataReceived.ToString());
if ((dataSent != 0) && (dataReceived != 0))
{
utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
}
else
{
string instance2 = pcc.GetInstanceNames()[0];
PerformanceCounter bandwidthCounter2 = new PerformanceCounter("Network Interface", "Current Bandwidth", instance2, ipAddress);
PerformanceCounter pcReceived2 = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance2, ipAddress);
PerformanceCounter pcSent2 = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance2, ipAddress);
float bandwidth2 = bandwidthCounter2.NextValue();
for (int index = 0; index < numberOfIterations; index++)
{
sendSum += pcSent2.NextValue();
receiveSum += pcReceived2.NextValue();
cpuSum += pcProcessorTime.NextValue();
}
float dataSent2 = sendSum;
float dataReceived2 = receiveSum;
utilization = (8 * (dataSent2 + dataReceived2)) / (bandwidth2 * numberOfIterations) * 100;
}
cpuSum = cpuSum / numberOfIterations;
IPHostEntry host = new IPHostEntry();
host = Dns.GetHostEntry(ipAddress);//ip Address is to be specified here
machineName = host.HostName;
endTime = DateTime.Now;
if (!frm.cbVerileriGosterme.Checked)
{
x.SubItems[1].Text = machineName;
x.SubItems[2].Text = threadNo.ToString();
x.SubItems[3].Text = pingDurumu;
x.SubItems[4].Text = pingSuresi.ToString();
x.SubItems[5].Text = (endTime - startTime).TotalSeconds.ToString();
x.SubItems[6].Text = utilization.ToString();
x.SubItems[7].Text = cpuSum.ToString();
x.SubItems[8].Text = pcKullanilabilirRam.NextValue().ToString();
x.SubItems[9].Text = "";
}
cc.sorgu = " EXECUTE [dbo].[prVeriKaydet] "
+ "'" + frm.taramaNo + "',"
+ "'" + ipAddress + "',"
+ "'" + machineName + "',"
+ pingSuresi.ToString().Replace(",", ".") + ","
+ (endTime - startTime).TotalSeconds.ToString().Replace(",", ".") + ","
+ utilization.ToString().Replace(",", ".") + ","
+ cpuSum.ToString().Replace(",", ".") + ","
+ pcKullanilabilirRam.NextValue().ToString().Replace(",", ".");
cc.Run(cc.sorgu, "");
}
catch (Exception ex)
{
endTime = DateTime.Now;
if (!veriGoster)
{
x.SubItems[2].Text = threadNo.ToString();
x.SubItems[3].Text = pingDurumu;
x.SubItems[4].Text = pingSuresi.ToString();
x.SubItems[5].Text = (endTime - startTime).TotalSeconds.ToString();
x.SubItems[5].Text = "0";
x.SubItems[6].Text = "0";
x.SubItems[7].Text = "0";
x.SubItems[8].Text = "0";
x.SubItems[9].Text = ex.Message;
}
}
}
lock (frm.progressBar1)
{
frm.progressBar1.Value++;
frm.lblIs.Text = frm.progressBar1.Value.ToString();
if (range - frm.nudThreads.Value < frm.progressBar1.Value)
{
frm.threadSayacKontrol--;
}
frm.tbThreadSayisi.Text = frm.threadSayacKontrol.ToString();
if (frm.progressBar1.Value == frm.progressBar1.Maximum)
{
frm.progressBar1.Value = 0;
frm.btnTara.Enabled = true;
frm.TheColumnSorter.CurrentColumn = 0;
frm.btnDurdurDevam.Enabled = false;
if (frm.cbSurekliTara.Checked)
{
frm.tara();
}
}
}
}
}
}
and then when I use bandwidthCounter
I get this error:
Object reference not set to an
instance of an object.
What is missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将实例放入静态字段中,并在字段初始值设定项中对其进行初始化。
例如:
You need to put the instance in a
static
field, and initialize it in the field initializer.For example:
如果您想在其他类中使用它,您可以将类搜索设为静态,并将其所有字段也设为静态。另外,您应该在使用对象“bandwidthCounter”之前实例化它。
If you want to use it in other classes you can make class search static and all its fields static as well. Also you should instantiate your object "bandwidthCounter" beforer playing with it.
我已经解决了我的问题,因为使用这个声明
,并且在使用这个格式之后
感谢每个答案
I have solved my problem as use this declaration
and after use this format
thanks to every answers