title: Performance Counter problem with multiple instances
body: <p>I have problem with win application when more then one network cards is plugged What can i do?</p>
  
  <p>This is the error:</p>
  
  <pre><code>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&amp; m)
     at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  </code></pre>
  
  <p>whole app code:</p>
  
  <pre><code>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 &amp; 1) == 1)
                  strState = "Modem connection";
              else if ((nState &amp; 2) == 2)
                  strState = "LAN connection";
              else if ((nState &amp; 4) == 4)
                  strState = "Proxy connection";
              else if ((nState &amp; 8) == 8)
                  strState = "Modem is busy with a non-Internet connection";
              else if ((nState &amp; 0x10) == 0x10)
                  strState = "Remote Access Server is installed";
              else if ((nState &amp; 0x20) == 0x20)
                  return "Offline";
              else if ((nState &amp; 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 &amp; 2) == 2 || (nState &amp; 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 &gt; 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 &gt; 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 &gt; 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 &gt; 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
  }
  </code></pre>