c# Memory leak system.timers

2019-09-16 13:34发布

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?

1条回答
疯言疯语
2楼-- · 2019-09-16 13:49

You are creating a new timer each time the button is clicked. Also, you are not keeping a reference to it, so it will be destroyed by the garbage collector. There is no need to start the timer on a new thread because the timer will raise the Elapsed event on a new thread.

class Form1 ...
{
    private System.Timers.Timer timer = null;

    public void start()
    {
    if (timer == null)
        {
        timer = new System.Timers.Timer(1000);
        timer.Elapsed += new ElapsedEventHandler(timerElapsed);
        }
    timer.Enabled = true;
    }

    ...
}

As far as a memory leak goes, I wouldn't assume there is a memory leak just because you see the memory usage fluctuating seemingly randomly while your application is running. That is normal behavior when you are running inside of a complex framework like .NET. Each time the timer fires, it's calling your connect method which creates new objects. Those objects will stay in memory until the garbage collector gets around to cleaning them up. As such, it's not at all surprising to see the memory creep up and then all of a sudden after a few minutes, drop back down again. I wouldn't suspect a problem unless it keeps growing out of control over a much longer period of time.

It's also strange the way you are using the StringBuilder class. What you are doing:

StringBuilder sb = new StringBuilder();
sb.Append(txtIPseg1.Text + "." + txtIPseg2.Text + "." + txtIPseg3.Text + "." + txtIPseg4.Text);
string address = sb.ToString();

is no better (in fact it's a bit worse), than just doing this:

string address = txtIPseg1.Text + "." + txtIPseg2.Text + "." + txtIPseg3.Text + "." + txtIPseg4.Text;

If you're looking for a more efficient, and possibly easier to read way to do it, try something like this

string address = string.Format("{0}.{1}.{2}.{3}", txtIPseg1.Text, txtIPseg2.Text, txtIPseg3.Text, txtIPseg4.Text);

Nothing, however, is jumping out at me as being anything that would cause a memory leak, so unless you have good reason to think so, I wouldn't worry about it.

查看更多
登录 后发表回答