Sign in to follow this  
stormwarestudios

C# - 'new' and (lack of) 'delete' operators

Recommended Posts

Hey all, I've been programming in C++ for about 10 years, and have recently (last couple of weeks) decided to learn C#. Currently I'm getting my head around the differences. So far so good. One question which came up in my mind to which I could not easily find the answer on the web, is the lack of a 'delete' operator (as in C++). Some of the searching I did revealed that memory heap allocation is automagically recycled by the .NET garbage collector "periodically". The question in my mind is, "how periodically?". The reason I ask this is that, for the test app I'm creating, it's possible to initialize the same thread repeatedly; if I am simply making multiple calls to 'new', will the allocated object recycle properly? How does .NET handle multiple allocations internally?

Share this post


Link to post
Share on other sites
Also check out the IDisposable interface, you need to use it if you're using unmanaged resources (ie, resources from a native library like directx, sdl, etc).

Share this post


Link to post
Share on other sites
The non-technical answer to "how periodically" is: 'when it can'. If your program is running 100%, you're going to run into trouble (if you're allocating memory). The more free time the framework has, the more freedom the collector has.

will the allocated object recycle properly? Yes.
How does .NET handle multiple allocations internally? The way it has been explained to me is by having a reference graph. As nodes (or branches) of data can no longer trace a reference back to the root of the graph, the collector culls them. No cyclic reference problems that can crop up with reference counting.


Share this post


Link to post
Share on other sites
The standard makes no stipulations, to my knowledge, about when the GC is run. However, the implementation typically runs the GC when it needs to; this usually means that an allocation request has been made and the gen0 section of the heap is full.

In other words, it'll happen when you use new, if necessary.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this