开发者

Overflow my memory, to force garbage collector?

How can I purposely overflow my memory, to force garbage collection? Can someone propose algorithm like this:

while ( garbage collector starts ) {
      overflow my memory with something easily disposable
}

Edit: To everyone that purposed GC.Collect method. I've always开发者_Python百科 tought, that GC can not be forced to occur programmaticaly. Guess, I was wrong. Thanks for the answers.


Better yet, how 'bout using GC.Collect? No need to synthesize a condition when there's an explicit feature available...

Also, note the GC.WaitForPendingFinalizers method that Adam Butler (comment above), ChristopheD (answer below), and Michael Petrotta (comment below) pointed out, which takes the next step. Scary quote from the documentation on that method, though: "The thread on which finalizers are run is unspecified, so there is no guarantee that this method will terminate." shudder


Apart from using GC.Collect: if you really need the garbage collection to be 'done' synchronously (blocking in other words), you could use GC.WaitForPendingFinalizers: http://msdn.microsoft.com/en-us/library/system.gc.waitforpendingfinalizers.aspx

Note that this may very well unnecessarily freeze your application temporarily.

The link also provides code that could trigger the garbage collector.


See this SO question: Best Practice for Forcing Garbage Collection in C#


Like this, for example:

int cnt = GC.CollectionCount(0);
while (GC.CollectionCount(0) == cnt) {
  string s = new String('*', 1000);
}

However, this will of course only run until a garbage collection occurs, but it might not be beacuse of the objects that are created, it could be for any reason.

If you just want the garbage collection to occur, the GC.Collect method would do that.

However, there is rarely any reason to force a garbage collection. Collections will occur when needed, you will usually only degrade performance by forcing collections.


Is there some reason GC.Collect() doesn't work for you? That forces garbage collection to occur.


Why not just use GC.Collect to force a garbage collection instead?


Can't you just call GC.Collect()

http://msdn.microsoft.com/en-us/library/system.gc.collect.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜