From: USB Device User on
Here is my code:
public bool Send(SafeFileHandle fileHandle, string information)
Byte[] writeBuffer = new byte[information.Length]; //initialize buffer
int iCount = 0;
while (iCount < information.Length)
writeBuffer[iCount] =

int bytesWritten = 0;
NativeOverlapped wo = new NativeOverlapped();
bool succeed = WriteFile(fileHandle, writeBuffer,
writeBuffer.Length, ref bytesWritten,ref wo);

if (succeed || Marshal.GetLastWin32Error() == ERROR_IO_PENDING)
return true;
return false;
catch (Exception e)
throw e;

I always got the exception when I debug WriteFile call:
InvalidOverlappedToPinvoke was detected
Message: An overlapped pointer (0x000000001CEAC258) that was not allocated
on the GC heap was passed via PInvoke to the Win32 function 'WriteFile' in
module 'kernel32.DLL'. If the AppDomain is shut down, this can cause heap
corruption when the async I/O completes. The best solution is to pass a
NativeOverlapped structure retrieved from a call to
System.Threading.Overlapped.Pack(). If the AppDomain exits, the CLR will keep
this structure alive and pinned until the I/O completes.

How can I fix it?
I tried the following and passed ptrUWO instead of wo into WriteFile. It did
not work.
NativeOverlapped wo = new NativeOverlapped();
wo.OffsetLow = 0;
wo.OffsetHigh = 0;
wo.EventHandle = IntPtr.Zero;
IntPtr ptrUWO = Marshal.AllocHGlobal(Marshal.SizeOf(wo));
Marshal.StructureToPtr(wo, ptrUWO, true);

I also tried the following and passed intOverlapped into WriteFile. It did
not work either.
IAsyncResult asyncResult;
/// Create a managed overlapped class
// We will set the file offsets later
Overlapped overlapped = new Overlapped(0, 0, IntPtr.Zero, asyncResult);
//// Pack the Overlapped class, and store it in the async result
NativeOverlapped intOverlapped;
intOverlapped = overlapped.UnsafePack(null);

Any help?Thanks