GC Behavior and CLR Thread Hijacking

前端 未结 1 783
广开言路
广开言路 2021-02-13 13:53

I was reading about the GC in the book CLR via C#, specifically about when the CLR wants to start a collection. I understand that it has to suspend the threads bef

相关标签:
1条回答
  • 2021-02-13 14:32

    'Safe Points' are where we are:

    1. Not in a catch block.
    2. Not inside a finally
    3. Not inside a lock
    4. Not inside p/invoke'd call (in managed code). Not running unmanaged code in the CLR.
    5. The memory tree is walkable.

    Point #5 is a bit confusing, but there are times when the memory tree will not be walkable. For example, after optimization, the CLR may new an Object and not assign it directly to a variable. According to the GC, this object would be a dead object ready to be collected. The compiler will instruct the GC when this happens to not run GC yet.

    Here's a blog post on msdn with a little bit more information: http://blogs.msdn.com/b/abhinaba/archive/2009/09/02/netcf-gc-and-thread-blocking.aspx

    EDIT: Well, sir, I was WRONG about #4. See here in the 'Safe Point' section. If we are inside a p/invoke (unmanaged) code section then it is allowed to run until it comes back out to managed code again.

    However, according to this MSDN article, if we are in an unmanaged portion of CLR code, then it is not considered safe and they will wait until the code returns to managed. (I was close, at least).

    0 讨论(0)
提交回复
热议问题