title: c# Memory leak system.timers
body: <p>I'm currently writing a program which interacts with I/O devices and needed a method of polling the device every x amount of seconds in order to check the in/out connections. To do this i've used a button which creates a thread to do the polling, using a timer and timer event handles. However, i notice that in the task manager, it is slowly eating up more memory as time goes by. Below is some snippets of code that are (i think) relevant to my problem.</p>
  
  <p>Button for creating thread:</p>
  
  <pre><code>private void btnConnect_Click(object sender, EventArgs e)
      {
          new Thread(start).Start();
      }
  </code></pre>
  
  <p>The thread that includes the timer:</p>
  
  <pre><code>        public void start()
      {
          timer = new System.Timers.Timer(1000);
          timer.Elapsed += new ElapsedEventHandler(timerElapsed);
          timer.Enabled = true;
      }
  </code></pre>
  
  <p>The ElapsedEventHandler:</p>
  
  <pre><code>public void timerElapsed(object sender, ElapsedEventArgs e)
      {
          connect();
      }
  </code></pre>
  
  <p>And finally the method connect();:</p>
  
  <pre><code>public void connect()
      {
          StringBuilder sb = new StringBuilder();
          sb.Append(txtIPseg1.Text + "." + txtIPseg2.Text + "." + txtIPseg3.Text + "." + txtIPseg4.Text);
          int Port = int.Parse(txtPort.Text);
          string address = sb.ToString();
  
          //send data
          byte[] bData = new byte[71];
          bData[0] = 240;
          bData[1] = 240;
          bData[2] = 0;
          bData[3] = 1;
          bData[68] = 240;
          bData[69] = 240;
          bData[70] = this.CalculateCheckSum(bData);
  
          try
          {
              byte[] result = this.SendCommandResult(address, Port, bData, 72);
              if (result != null)
              {
                  this.Invoke((MethodInvoker)delegate
                  {
                      txtOutput1.Text = (result[4] == 0x00 ? "HIGH" : "LOW"); // runs on UI thread
                  });
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.ToString());
          }
  
      }
  </code></pre>
  
  <p>I'm pretty sure the leak is either coming from the timer, or the anon delegate used in the method connect();, anyone have any ideas?</p>