예제 #1
0
        public unsafe void Read(byte[] readBuffer)
        {
            uint bytesRead = 0;

            fixed(byte *outBuffer = readBuffer)
            {
                var success = false;

                try
                {
                    success = InteropKernel32.ReadFile(_readHandle,
                                                       outBuffer,
                                                       (uint)readBuffer.Length,
                                                       ref bytesRead,
                                                       null);
                }
                catch (ObjectDisposedException)
                {
                    throw new Exception("File handle already closed");
                }

                if (!success)
                {
                    HandleIOError(false);
                }
            }
        }
예제 #2
0
        public unsafe void ReadOverlapped(byte[] readBuffer)
        {
            var  completedEvent = new ManualResetEvent(false);
            uint bytesRead      = 0;
            var  inOverlapped   = new Overlapped();

            inOverlapped.EventHandleIntPtr = completedEvent.SafeWaitHandle.DangerousGetHandle();
            NativeOverlapped *inNativeOverlapped = inOverlapped.Pack(null, null);

            try
            {
                // send the data to the device
                fixed(byte *outBuffer = readBuffer)
                {
                    var success = false;

                    try
                    {
                        success = InteropKernel32.ReadFile(_readHandle,
                                                           outBuffer,
                                                           (uint)readBuffer.Length,
                                                           ref bytesRead,
                                                           inNativeOverlapped);
                    }
                    catch (ObjectDisposedException)
                    {
                        throw new Exception("File handle already closed");
                    }

                    if (!success)
                    {
                        HandleIOError(true);

                        CancelOverlapped(_readHandle, completedEvent);
                    }
                }
            }
            finally
            {
                // clean up
                Overlapped.Free(inNativeOverlapped);
            }
        }