bbosak
bbosak

Reputation: 5529

MemoryStream.SetLength(0) and MemoryStream.Capacity = 0 don't clear used memory

I have a program that streams media, which creates two huge MemoryStreams, and then needs to zero them when done. The problem is, the memory does not seem to be reclaimed after I call BOTH MemoryStream.SetLength(0); and MemoryStream.Capacity = 0. GC.Collect() seems to solve the problem, but I have heard this is bad programming practice, because it causes all threads in the application to hang; although hung threads would not be a problem for the short time it would take to clear the memory. However, it would be nice if there was another workaround to the problem. Any suggestions?

Upvotes: 2

Views: 1926

Answers (4)

Jason
Jason

Reputation: 5027

Can you call dispose on the memory streams? Otherwise i would say that unless perf is unacceptable when you do a gc.collect, go ahead and do it. We had a similar situation where the customer found the "let the gc do its thing" explanation unacceptable. Esp if it does no harm, do what the customer wants.

Upvotes: 0

user541686
user541686

Reputation: 210427

If you really need manual management of the memory, use UnmanagedMemoryStream with memory allocated by something like Marshal.AllocHGlobal.

Upvotes: 0

Peter O.
Peter O.

Reputation: 32878

You can just fill the memory with zeros with the Write method, then call Flush, then call the MemoryStream's Close or Dispose method, if you're worried that the data remaining in the stream will remain in memory after it's disposed. (Yes, it will be slower for huge memory streams, but you should only be concerned of this after determining, through profiling, whether it causes a real performance problem in your program.)

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292405

GC.Collect() seems to solve the problem

So there is no problem... Why do you think you need to force the GC to collect the memory at once? It will be done when the system deems it necessary. Don't try to outsmart the GC ;)

Upvotes: 5

Related Questions