2010-07-19 70 views
0

當多個網卡插上時,我遇到win應用程序的問題我該怎麼辦?多個實例的性能計數器問題

這是錯誤:

System.InvalidOperationException: Instance 'Citrix XenServer PV Ethernet Adapter #2' does not exist in the specified Category. 
    at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName) 
    at System.Diagnostics.PerformanceCounter.NextSample() 
    at System.Diagnostics.PerformanceCounter.NextValue() 
    at CurrencyApp.Converter.timerMemProcNetwork_Tick(Object sender, EventArgs e) 
    at System.Windows.Forms.Timer.OnTick(EventArgs e) 
    at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m) 
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 

整個應用程序的代碼:

public partial class Converter : Form 
{ 
    #region Properties 

    private int NumOfRepeats; 
    private int NumberOfErrorRows; 
    private int NumberOfUpdatedRows; 
    private int NumberofNewRows; 
    private string Status; 
    private PerformanceCounter counterReceived; 
    private PerformanceCounter counterSent; 
    private PerformanceCounter cpuCounter; 
    private int nByteCountReceive; 
    private int nByteCountSend; 
    private int nCPUUsage; 
    private int nFirstTimeCheckConnection; 
    private float nFreeMemory; 
    private PerformanceCounter ramCounter; 

    private int ByteCountReceive 
    { 
     get { return nByteCountReceive; } 
     set 
     { 
      nByteCountReceive = value; 
      statusBarPanelByteReceive.Text = "Receive:" + Commas(nByteCountReceive/1024 + 1) + " KB"; 
     } 
    } 

    private int ByteCountSend 
    { 
     get { return nByteCountSend; } 
     set 
     { 
      nByteCountSend = value; 
      statusBarPanelByteSend.Text = "Send:" + Commas(nByteCountSend/1024 + 1) + " KB"; 
     } 
    } 

    private float FreeMemory 
    { 
     get { return nFreeMemory; } 
     set 
     { 
      nFreeMemory = value; 
      statusBarPanelMem.Text = nFreeMemory + " Mb Available"; 
     } 
    } 

    private int CPUUsage 
    { 
     get { return nCPUUsage; } 
     set 
     { 
      nCPUUsage = value; 
      statusBarPanelCPU.Text = "CPU usage " + nCPUUsage + "%"; 
     } 
    } 

    private static IDaoFactory DaoFactory 
    { 
     get { return new NHibernateDaoFactory(ConfigurationManager.AppSettings["NHibernateConfigPath"]); } 
    } 

    #endregion 

    #region Methods 

    public Converter() 
    { 
     InitializeComponent(); 
     InitialiseCounterRamNetwork(); 
     InitializeBackgroundWorker(); 
    } 

    [DllImport("wininet")] 
    private static extern int InternetGetConnectedState(ref int lpdwFlags, int dwReserved); 

    [DllImport("wininet")] 
    private static extern int InternetAutodial(int dwFlags, int hwndParent); 

    private static string InternetGetConnectedStateString() 
    { 
     string strState = ""; 
     try 
     { 
      int nState = 0; 
      // check internet connection state 
      if (InternetGetConnectedState(ref nState, 0) == 0) 
       return "You are currently not connected to the internet"; 
      if ((nState & 1) == 1) 
       strState = "Modem connection"; 
      else if ((nState & 2) == 2) 
       strState = "LAN connection"; 
      else if ((nState & 4) == 4) 
       strState = "Proxy connection"; 
      else if ((nState & 8) == 8) 
       strState = "Modem is busy with a non-Internet connection"; 
      else if ((nState & 0x10) == 0x10) 
       strState = "Remote Access Server is installed"; 
      else if ((nState & 0x20) == 0x20) 
       return "Offline"; 
      else if ((nState & 0x40) == 0x40) 
       return "Internet connection is currently configured"; 

      // get current machine IP 
      string strHostName = Dns.GetHostName(); 
      string ip = "/"; 

      IPAddress[] addrs = Dns.GetHostAddresses(strHostName); 
      foreach (var addr in addrs) 
      { 
       if (addr.AddressFamily.ToString() == "InterNetwork") 
       { 
        ip = addr.ToString(); 
       } 
      } 
      strState += ", Machine IP: " + ip; 
     } 
     catch (Exception ex) 
     { 
      return ex.ToString(); 
     } 

     return strState; 
    } 

    private void ConnectionInfo() 
    { 
     try 
     { 
      int nState = 0; 
      if (InternetGetConnectedState(ref nState, 0) == 0) 
      { 
       if (nFirstTimeCheckConnection++ == 0) 
        // ask for dial up or DSL connection 
        if (InternetAutodial(1, 0) != 0) 
         // check internet connection state again 
         InternetGetConnectedState(ref nState, 0); 
      } 
      if ((nState & 2) == 2 || (nState & 4) == 4) 
       // reset to reask for connection agina 
       nFirstTimeCheckConnection = 0; 

      statusBarPanelInfo.Text = InternetGetConnectedStateString(); 
     } 
     catch (Exception ex) 
     { 
      statusBarPanelInfo.Text = ex.ToString(); 
     } 
    } 

    private void InitialiseCounterRamNetwork() 
    { 
     cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); 
     ramCounter = new PerformanceCounter("Memory", "Available MBytes", true); 
     string instance = "MS TCP Loopback interface"; 

     NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 

     foreach (NetworkInterface nic in nics) 
     { 
      if (nic.Description == "MS TCP Loopback interface") 
       continue; 

      if (nic.OperationalStatus.ToString() == "Up") 
      { 
       instance = nic.Description; 
       break; 
      } 
     } 

     counterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); 
     counterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); 
    } 

    private void btnStartCurrencyConverter_Click(object sender, EventArgs e) 
    { 
     NumOfRepeats = 0; 
     NumberOfErrorRows = 0; 
     NumberofNewRows = 0; 
     NumberOfUpdatedRows = 0; 
     txtStatus.Text = "Start: " + DateTime.Now + Environment.NewLine; 

     lblNumberOfUpdatedRows.Text = NumberOfUpdatedRows.ToString(); 
     lblNumberofNewRows.Text = NumberofNewRows.ToString(); 

     btnStartCurrencyConverter.Enabled = false; 
     btnCancel.Enabled = true; 

     if (!bwCrawler.IsBusy) 
      bwCrawler.RunWorkerAsync(); 
    } 

    private static string Commas(int nNum) 
    { 
     string str = nNum.ToString(); 
     int nIndex = str.Length; 
     while (nIndex > 3) 
     { 
      str = str.Insert(nIndex - 3, ","); 
      nIndex -= 3; 
     } 
     return str; 
    } 

    private void InitializeBackgroundWorker() 
    { 
     bwCrawler.DoWork += bwCrawler_DoWork; 
     bwCrawler.ProgressChanged += bwCrawler_ProgressChanged; 

     bwCrawler.WorkerReportsProgress = true; 
     bwCrawler.WorkerSupportsCancellation = true; 
    } 

    private void CurrencImport() 
    { 
     CurrencyConvertorSoapClient client = new CurrencyConvertorSoapClient(); 

     string[] curr1 = Enum.GetNames(typeof (Currency)); 
     string[] curr2 = Enum.GetNames(typeof (Currency)); 
     int i = 0; 
     int j = 0; 
     int workComplete = curr1.Length*curr2.Length; 
     int workDone = 0; 
     decimal percentComplete = 0; 

     foreach (var c1 in curr1) 
     { 
      foreach (var c2 in curr2) 
      { 
       start_of_loop: 
       { 
       } 
       try 
       { 
        Currency cEnum1 = (Currency) Enum.Parse(typeof (Currency), c1); 
        Currency cEnum2 = (Currency) Enum.Parse(typeof (Currency), c2); 
        double rate = client.ConversionRate(cEnum1, cEnum2); 

        ICurrenciesDao currenciesDao = DaoFactory.GetCurrenciesDao(); 

        Currencies currencyExist = currenciesDao.GetConversionRateByFromCurrencyToCurrency(c1, c2); 

        if (currencyExist != null) 
        { 
         // update if row exist 
         currencyExist.ConversionRate = Convert.ToDecimal(rate); 
         currenciesDao.SaveOrUpdate(currencyExist); 
         currenciesDao.CommitChanges(); 

         i++; 
         NumberOfUpdatedRows = i; 
        } 
        else 
        { 
         // write new row 
         Currencies currencyNew = new Currencies(c1, c2, Convert.ToDecimal(rate), DateTime.Now); 
         currenciesDao.Save(currencyNew); 
         currenciesDao.CommitChanges(); 

         j++; 
         NumberofNewRows = j; 
        } 

        Status = c1 + " - " + c2 + ": " + rate; 
       } 
       catch (Exception ex) 
       { 
        Thread.Sleep(200000); 

        if (NumOfRepeats > 50) 
        { 
         Status = ex.ToString(); 
         NumberOfErrorRows = 1; 
        } 
        else 
         goto start_of_loop; 
       } 

       if (bwCrawler.CancellationPending) 
        break; 

       workDone++; 
       percentComplete = (workDone/workComplete)*100; 
       bwCrawler.ReportProgress(Convert.ToInt32(percentComplete)); 
       NumOfRepeats = 0; 

       if (percentComplete == 100) 
        break; 
      } 

      if (bwCrawler.CancellationPending) 
       break; 

      if (percentComplete == 100) 
       break; 
     } 
    } 

    private void btnCancel_Click(object sender, EventArgs e) 
    { 
     if (bwCrawler.IsBusy) 
     { 
      //Initiate cancel 
      bwCrawler.CancelAsync(); 
     } 

     btnCancel.Enabled = false; 
     btnStartCurrencyConverter.Enabled = true; 

     txtStatus.AppendText("Canceled: " + DateTime.Now + Environment.NewLine); 
    } 

    private void bwCrawler_DoWork(object sender, DoWorkEventArgs e) 
    { 
     CurrencImport(); 
    } 

    private void bwCrawler_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 
     btnCancel.Enabled = false; 
     btnStartCurrencyConverter.Enabled = true; 

     if (e.Cancelled) 
     { 
      txtStatus.AppendText("Canceled" + Environment.NewLine); 
     } 
     else if (e.Error != null) 
     { 
      txtStatus.AppendText("Error. Details: " + (e.Error) + Environment.NewLine); 
     } 
     else 
     { 
      txtStatus.AppendText("Finished: " + DateTime.Now + Environment.NewLine); 
     } 
    } 

    private void bwCrawler_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     if (NumberOfErrorRows > 0) 
     { 
      if (bwCrawler.IsBusy) 
      { 
       //Initiate cancel 
       bwCrawler.CancelAsync(); 
      } 
     } 

     lblNumberOfUpdatedRows.Text = NumberOfUpdatedRows.ToString(); 
     lblNumberofNewRows.Text = NumberofNewRows.ToString(); 
     txtStatus.AppendText(Status + Environment.NewLine); 

     if (txtStatus.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length > 200) 
     { 
      txtStatus.Text = string.Empty; 
     } 
    } 

    private void timerConnectionInfo_Tick(object sender, EventArgs e) 
    { 
     ConnectionInfo(); 
    } 

    private void timerMemProcNetwork_Tick(object sender, EventArgs e) 
    { 
     FreeMemory = ramCounter.NextValue(); 
     CPUUsage = Convert.ToInt32(cpuCounter.NextValue()); 
     ByteCountReceive = Convert.ToInt32(counterReceived.NextValue()); 
     ByteCountSend = Convert.ToInt32(counterSent.NextValue()); 
    } 

    #endregion 
} 
+3

請發佈創建錯誤的實際代碼,而不僅僅是錯誤。 – 2010-07-19 19:15:14

+0

我不知道哪個部分創建錯誤becouse在生產服務器我們有2個網卡。我的電腦裏只有一個!我可以複製完整的應用程序代碼。 – senzacionale 2010-07-19 19:19:19

+0

在我看來,在你的代碼的某個地方,你必須指定適配器的名稱... – Luiscencio 2010-07-19 19:20:50

回答

2

您正在閱讀爲其指定不存在實例的性能計數器。從實例名稱判斷,您嘗試閱讀「網絡接口」類別。確保您在正確的機器上閱讀正確的類別。發佈代碼以初始化timerMemProcNetwork_Tick中引用的性能計數器對象。

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 
foreach (NetworkInterface nic in nics) 
{ 
    ... 
    counterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); 
    ... 
} 

此代碼混合了蘋果和橘子。在「網絡接口」類別上使用PerformanceCounterCategory.GetInstanceNames以獲取有效實例的列表。

+0

thx爲您的答案。代碼位於頂部。 – senzacionale 2010-07-19 19:26:33

+0

看我的編輯。 'NetworkInterface.GetAllNetworkInterfaces'不是獲取性能計數器實例名稱的可靠方法。使用'PerformanceCounterCategory.GetInstanceNames',確實如此:檢索實例列表。 – 2010-07-19 19:28:19

+0

Thx尋求幫助。你爲我節省了很多時間。 – senzacionale 2010-07-19 20:31:56