Does the .dispose() method do anything at all?

前端 未结 4 1892
鱼传尺愫
鱼传尺愫 2021-02-09 20:32

I was experimenting with ways to get rid of some memory leaks within my application the other day when I realized that I know virtually nothing about cleaning up my resources.

4条回答
  •  时光说笑
    2021-02-09 21:29

    IDisposable and thus Dispose is not used to reduced memory pressure, although in some cases it might, but instead used for deterministic cleanup.

    Consider this, you construct an object that maintains an active and open connection to your database server. This connection uses resources, both on your machine, and the server.

    You could of course just leave the object be when you're done with it, and eventually it'll get picked up by the garbage collector, but suppose you want to make sure at least the resources gets freed, and thus the connection closed, when you're done with it. This is where IDisposable.Dispose comes into play.

    It is used to clean up resources managed by the object.

    It will, however, not free the managed memory allocated to the object. This is still left to the garbage collector, that will kick in at some later time to do that.

    Do you actually have a memory problem, or do you just look at the memory usage in Task Manager or similar and go "that's a bit high."?

    If the latter, then you should just leave it be for now. .NET will run garbage collection more often if you have less memory available, so unless you're in a situation where you get, or might suspect you will get soon, a memory overflow condition, you're probably not going to have any problems.

    Let me explain what I mean by "run less often".

    If you have 8GB of memory in your machine, and only have Windows and Notepad running, most of that memory will be available. When you now run your program, even if it loads minor data blocks into memory, you can keep doing that for a long time, and memory usage will steadily grow. Exactly when the GC will kick in and try to reduce your memory footprint I don't know, but I can almost guarantee you that you will wonder why it gets so high.

    Let's just for the sake of the argument say that your program will eventually use 2GB of memory.

    Now, if you run your program on a machine that has less memory available, GC will occur more often, and will kick in on a lower limit, which might keep the memory usage below 500MB or possibly even less.

    The important part to note here is that in order for you to get an accurate picture of how much memory application actually requires, then you can't rely on Task Manager or similar ways to measure it, you need something more targetted.

提交回复
热议问题