crash after upgrade
Consider the following code which closes an overlapped I/O serial handle during application shutdown.
It works fine under .NET 2.0 but after switching to .NET 4.0 it crashes on the CloseHandle. Removing CancelIO doesnt help.
Does anyone know what the correct way is to close an overlapped I/O handle? And why is there the difference between NET2.0 and 4.0?
Can't speak for .net, but in C/C++, you should call GetOverlappedResult() with the last param TRUE. This ensures that any pending async operations are complete before closing the handle.
Knowing the exception that's thrown when it crashes would help determine the cause...
It's an access violation, not a .NET exception
GetOverlappedResult helped indeed, there were still bytes pending to be written. Thanks!
Originally Posted by Codeplug
So the correct order of closing a serial port would be:
GetOverlappedResult(hPort, ptrUWO, out sent, checkSends)
Hmmm it still sometimes crashes only a lot less
While overlapped IO is pending, you need to make sure that your OVERLAPPED structure, Event handle, and src/dest buffers are all valid. So before any of those resources are released, you need to make sure that all pending IO has completed and the easy way to do that is to call GetOverlappedResult with the last param TRUE.
If you are ready to "get out" and don't care about any pending IO then you can:
GetOverlappedResult( , , , TRUE)
If you call GetOverlappedResult( , , , TRUE) first, then there is no pending IO so CancelIo() doesn't need to be called.