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.
Button for creating thread:
private void btnConnect_Click(object sender, EventArgs e)
{
new Thread(start).Start();
}
The thread that includes the timer:
public void start()
{
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
timer.Enabled = true;
}
The ElapsedEventHandler:
public void timerElapsed(object sender, ElapsedEventArgs e)
{
connect();
}
And finally the method connect();:
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());
}
}
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?