开发者

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?


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 ;)


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.)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜