What is an “Async Pinned Handle”?

后端 未结 1 1805
我在风中等你
我在风中等你 2020-11-30 09:48

I\'m trying to investigate a really nasty software crash which is possibly related to a managed heap corruption (since it happens during a garbage collection). Using WinDbg

相关标签:
1条回答
  • 2020-11-30 10:30

    Async pinned handles are strongly correlated with overlapped I/O in Windows. Which supports asynchronous reading and writing with ReadFile and WriteFile, using the OVERLAPPED argument. The device driver stores the passed buffer pointer and directly reads/writes from/to the buffer, entirely asynchronously from the program's operation. The managed wrapper methods are BeginRead and BeginWrite.

    If the buffer is allocated in the GC heap then it needs to be pinned until the driver finishes using the buffer. Having the GC move the buffer while the driver is working on the I/O transfers is disastrous, writes would produce junk and reads would corrupt the GC heap, pinning is required to prevent the buffer from being moved while the driver is using it.

    Pinned objects are pretty unpleasant, they give the garbage collector a hard time to work around the rock in the road when it compacts the heap. A necessary evil here, the only possible way to get ahead is to leave the buffer pinned for as short amount of time as possible.

    Async pinned handles are marked specially to allow the CLR to automatically unpin the buffer on I/O completion. As quickly as possible, when the I/O completion port signals completion and thus not having to wait for the client code to execute the callback and unpin the buffer. Which could take a while when there are lots of threadpool threads in flight. It is a micro-optimization that tends to turn into a macro one when you have, say, a web server that handles tens of thousands of client requests.

    It is only ever used for objects of type System.Threading.OverlappedData, an internal class in mscorlib.dll that the CLR has special knowledge of and is the managed facsimile for the native OVERLAPPED structure that the Windows api functions use.

    Long story short, all you really know is that there's an overlapped I/O pending if you see the handle count at 1 when it crashes. Having any native code that does overlapped I/O with gc allocated buffers that are not pinned is otherwise indeed a good way to destroy the heap. You have rather a lot of pinned handles btw.

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