C# AddMemoryPressure performance
Does C# AddMemoryPressure call add a connection to the specific object it's being invoked for? I've seen it show up a lot in our performance traces, and I want to batch together calls every 10MB or so, but if it inspects the stack to attach t开发者_JAVA技巧he pressure information to a specific object it thinks is being allocated then that won't work
AddMemoryPressure only tells the GC that more memory is used than what is visible to the GC. It is not connected to any object.
Using AddMemoryPressure will probably cause the clean-ups to run more often but I don't know if that is good or bad for performance. I assume it increases the risk that a clean-up is ran in the middle of something instead of only running on idle.
This line from the documentation is probably what you need
"In more complicated scenarios, where the unmanaged memory allocation changes substantially during the lifetime of the managed object, you can call the AddMemoryPressure and RemoveMemoryPressure methods to communicate these incremental changes to the runtime."
As long as you remove the same amount as you add you can call the methods as you like.
The method is used in pair with RemoveMemoryPressure, to warn the garbage collector of unmanaged resources that might consume a lot of memory.
If a managed object (like a class), uses unmanaged methods, it should inform the garbage collector of it. That way the garbage collector knows how much memory is really in use, and therefore can give priorities to cleaning it up. The garbage collector cleans up periodically, but when you use AddMemoryPressure, it might clean up earlier, to avoid OutOfMemory errors. It's important to add the same amount of memory pressure as that you remove!
精彩评论