How to use win32::WriteFile when there is possible fail option?
<p>I using the win32 method 'WriteFile' to do some work in C# ( version .net 4.0 ) 
I need to wait till the method will finish the task and to do it i using 'WaitForSingleObject' .</p>

<p>But there is some cases that the method 'WriteFile' is fail ==> so for this case i gave the 'WaitForSingleObject' 30 seconds time-out. </p>

<p>But after this 30 seconds i get off the scope of the method 'WriteFile' => there if the GC will run the objects that i gave as arguments in the method 'WriteFile' will be collected and when this happened i get a crash !!! - </p>

<p>I checked the dump and its saying the i have memory corruption. 
When i remove the line of 'WriteFile' the crash is not appears. </p>

<p>How to solve it ?!
I can't make the variables of the 'WriteFile' method to be global and i must leave them as local variables. </p>

<p>The code </p>

<pre><code>      public void foo(byte[] bufferToWrite)
      {
          unsafe
          {

          NativeOverlapped overlapped = new NativeOverlapped()
          {
                EventHandle = eventHandle,
                OffsetLow   = ( int )( s       &amp; 0xffffffff ),
                OffsetHigh  = ( int )( s &gt;&gt; 32 &amp; 0xffffffff )
          };

          GCHandle gch = GCHandle.Alloc( bufferToWrite, GCHandleType.Pinned );
          IntPtr ptr = new IntPtr( ( void* )gch.AddrOfPinnedObject() );

          bResult = WriteFile( handle, ptr, length, ref bytesWritten, &amp;overlapped );
          if( bResult == ERROR_SUCCESS == || bResult == ERROR_IO_PENDING )
          {
                dwResult = WaitForSingleObject( EventHandle, 30000 );
          }
          }
 } 
</code></pre>
