EndRead() public method

public EndRead ( IAsyncResult asyncResult ) : int
asyncResult IAsyncResult
return int
Example #1
1
        static void Main(string[] args)
        {
            //AsyncReadOneFile();

            //AsyncReadMultiplyFiles();

            FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
               FileAccess.Read, FileShare.Read, 1024,
               FileOptions.Asynchronous);

            Byte[] data = new Byte[100];

            IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);

            while (!ar.IsCompleted)
            {
                Console.WriteLine("Операция не завершена, ожидайте...");
                Thread.Sleep(10);
            }

            Int32 bytesRead = fs.EndRead(ar);

            fs.Close();

            Console.WriteLine("Количество считаных байт = {0}", bytesRead);
            Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
        }
Example #2
0
        private static void AsyncReadOneFileCallBackAnonimus()
        {
            Byte[] data = new Byte[100];

            Console.WriteLine("Основной поток ID = {0}",
               Thread.CurrentThread.ManagedThreadId);

            FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
                                           FileAccess.Read, FileShare.Read, 1024,
                                           FileOptions.Asynchronous);

            fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar)
            {
                Console.WriteLine("Чтение в потоке {0} закончено",
                Thread.CurrentThread.ManagedThreadId);

                Int32 bytesRead = fs.EndRead(ar);

                fs.Close();

                Console.WriteLine("Количество считаных байт = {0}", bytesRead);
                Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));

                Console.ReadLine();
            }, null);
            Console.ReadLine();
        }
        private void ReadFileAsync(Action <byte[]> callback)
        {
            _fileStream.BeginRead(_fileBuffer, 0, _fileBuffer.Length,
                                  c =>
            {
                if (this._isStopTask)
                {
                    return;
                }

                int readlenght = _fileStream.EndRead(c);
                if (readlenght != _fileBuffer.Length)
                {
                    IsReadEnd();
                    byte[] buf = new byte[readlenght];
                    Array.Copy(_fileBuffer, 0, buf, 0, readlenght);
                    callback?.Invoke(buf);
                }
                else
                {
                    IsReadEnd();
                    callback?.Invoke(_fileBuffer);
                }
                void IsReadEnd()
                {
                    if (_fileStream.Length == _fileStream.Position)
                    {
                        this.CloseFileStream();
                    }
                }
            }, null);
        }
Example #4
0
 protected void ReadCompleted(IAsyncResult iResult)
 {
     byte[] arrBuff = (byte[])iResult.AsyncState;
     try
     {
         File.EndRead(iResult);  // call end read : this throws any exceptions that happened during the read
         try
         {
             InputReport oInRep = CreateInputReport(); // Create the input report for the device
             oInRep.SetData(arrBuff);                  // and set the data portion - this processes the data received into a more easily understood format depending upon the report type
             HandleDataReceived(oInRep);               // pass the new input report on to the higher level handler
         }
         finally
         {
             BeginAsyncRead();   // when all that is done, kick off another read for the next report
         }
     }
     catch (IOException ex)
     {
         HandleDeviceRemoved();
         if (OnDeviceRemoved != null)
         {
             OnDeviceRemoved(this, new EventArgs());
         }
         Dispose();
     }
 }
        static void Main(string[] args)
        {
            // open filestream for asynchronous read
            FileStream fs = new FileStream("somedata.dat", FileMode.Open,
                FileAccess.Read, FileShare.Read, 1024,
                FileOptions.Asynchronous);
            // byte array to hold 100 bytes of data
            Byte[] data = new Byte[100];

            // initiate asynchronous read operation, reading first 100 bytes
            IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);

            // could do something in here which would run alongside file read...

            // check for file read complete
            while (!ar.IsCompleted)
            {
                Console.WriteLine("Operation not completed");
                Thread.Sleep(10);
            }

            // get the result
            int bytesRead = fs.EndRead(ar);
            fs.Close();

            Console.WriteLine("Number of bytes read={0}", bytesRead);
            Console.WriteLine(BitConverter.ToString(data, 0, bytesRead));
        }
Example #6
0
 public void EndReadThrowsForNullAsyncResult()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
     {
         Assert.Throws<ArgumentNullException>("asyncResult", () => fs.EndRead(null));
     }
 }
Example #7
0
        public void ReadAsync(Action <byte[]> callback)
        {
            if (!Exists)
            {
                throw new System.IO.IOException("file is not exists");
            }

            //todo:需要测试
            System.IO.FileStream fs = new System.IO.FileStream(FullName,
                                                               System.IO.FileMode.Open,
                                                               System.IO.FileAccess.Read,
                                                               System.IO.FileShare.None,
                                                               bufferSize: 1024,
                                                               useAsync: true
                                                               );

            byte[] data = new byte[fs.Length];
            fs.BeginRead(data, 0, data.Length, (result) => {
                fs.EndRead(result);
                data = Decrypted(data);
                fs.Close();
                fs.Dispose();
                callback.Invoke(data);
            }, null);
        }
Example #8
0
 /// <summary>
 /// Demonstrates the use of the APM with files, through the FileStream class.
 /// This method performs asynchronous reads and writes to copy data from an input
 /// file to an output file.  Reads and writes are interlaced, and proceed in chunks
 /// of 8KB at a time (displaying progress to the console).
 /// </summary>
 static void APMWithFiles()
 {
     FileStream reader = new FileStream("sample.txt", FileMode.Open);
     FileStream writer = new FileStream("sample2.txt", FileMode.Create);
     byte[] buffer1 = new byte[8192], buffer2 = new byte[8192];
     IAsyncResult ar1, ar2 = null;
     while (true)
     {
         ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null);
         while (!ar1.IsCompleted)
         {
             Console.Write("R");
         }
         if (ar2 != null)
         {
             while (!ar2.IsCompleted)
             {
                 Console.Write("W");
             }
         }
         int bytesRead;
         if ((bytesRead = reader.EndRead(ar1)) == 0)
             break;  //No more data to read
         if (ar2 != null)
         {
             writer.EndWrite(ar2);
         }
         Array.Copy(buffer1, buffer2, bytesRead);
         ar2 = writer.BeginWrite(buffer2, 0, bytesRead, null, null);
     }
     Console.WriteLine();
     Console.WriteLine();
 }
Example #9
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (_m_disposed)
            {
                throw ADP.ObjectDisposed(this);
            }

            return(_m_fs.EndRead(asyncResult));
        }
Example #10
0
 public static void ApplyIPSPatch(string romname, string patchname)
 {
     // Noobish Noobsicle wrote this IPS patching code
     // romname is the original ROM, patchname is the patch to apply
     FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     int lint = (int)ipsstream.Length;
     byte[] ipsbyte = new byte[ipsstream.Length];
     byte[] rombyte = new byte[romstream.Length];
     IAsyncResult romresult;
     IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null);
     ipsstream.EndRead(ipsresult);
     int ipson = 5;
     int totalrepeats = 0;
     int offset = 0;
     bool keepgoing = true;
     while (keepgoing == true)
     {
         offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2];
         ipson++;
         ipson++;
         ipson++;
         if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0)
         {
             ipson++;
             ipson++;
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             byte[] repeatbyte = new byte[totalrepeats];
             for (int ontime = 0; ontime < totalrepeats; ontime++)
                 repeatbyte[ontime] = ipsbyte[ipson];
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson++;
         }
         else
         {
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson = ipson + totalrepeats;
         }
         if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70)
             keepgoing = false;
     }
     romstream.Close();
     ipsstream.Close();
 }
Example #11
0
        static void Main(string[] args)
        {
            byte[] buf = new byte[128];

            FileStream file = new FileStream(@"D:\hello.py", FileMode.Open);
            IAsyncResult ar = file.BeginRead(buf, 0, 128, null, null);
            Thread.Sleep(1000); // do other things
            int n = file.EndRead(ar);
            file.Close();

            string s = Encoding.UTF8.GetString(buf, 0, n);
            Console.WriteLine("Readed: {0}, {1}", n, s);
        }
Example #12
0
        static void DemoAsync()
        {
            using (var fs = new FileStream(@"C:\temp\foo.txt", FileMode.Open))
            {
                byte[] content = new byte[fs.Length];
                IAsyncResult ar = fs.BeginRead(content, 0, (int)fs.Length, ReadCompletionCallback, null);

                Console.WriteLine("控制流程回到主執行緒,執行其他工作...");
                Thread.Sleep(1500);   // 模擬執行其他工作需要花費的時間。

                // 等到需要取得結果時,呼叫 EndRead 方法(會 block 當前執行緒)
                int bytesRead = fs.EndRead(ar);
                Console.WriteLine("一共讀取了 {0} bytes。", bytesRead);
            }
        }
Example #13
0
 static public int EndRead(IntPtr l)
 {
     try {
         System.IO.FileStream self = (System.IO.FileStream)checkSelf(l);
         System.IAsyncResult  a1;
         checkType(l, 2, out a1);
         var ret = self.EndRead(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Example #14
0
        //Метод считывания из одного файла
        private static void AsyncReadOneFile()
        {
            FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open, FileAccess.Read,
                                            FileShare.Read, 1024, FileOptions.Asynchronous);
            Byte[] data = new Byte[100];
            // Начало асинхронной операции чтения из файла FileStream. 
            IAsyncResult ar = fs.BeginRead(data, 0, data.Length, null, null);
            // Здесь выполняется другой код... 
            // Приостановка этого потока до завершения асинхронной операции 
            // и получения ее результата. 
            Int32 bytesRead = fs.EndRead(ar);
            // Других операций нет. Закрытие файла. 
            fs.Close();
            // Теперь можно обратиться к байтовому массиву и вывести результат операции. 
            Console.WriteLine("Количество прочитаных байт = {0}", bytesRead);

            Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
        }
Example #15
0
        void OnReadDone(IAsyncResult ar)
        {
            int result = stream.EndRead(ar);

            if (result > 0)
            {
                loop.NonBlockInvoke(delegate {
                    RaiseData(new ByteBuffer(readBuffer, 0, result));
                    ReadNextBuffer();
                });
            }
            else
            {
                loop.NonBlockInvoke(delegate {
                    PauseReading();
                    RaiseEndOfStream();
                });
            }
        }
Example #16
0
        public static void CopyFile(String sourcePath, String destinationPath, Action<String, String, Exception> completed)
        {
            Stream source = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
            Stream destination = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);
            byte[] buffer = new byte[0x1000];
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);

            Action<Exception> cbCompleted = e =>
            {
                if (completed != null) asyncOp.Post(delegate
                     {
                         source.Close();
                         destination.Close();
                         completed(sourcePath, destinationPath, e);
                     }, null);
            };

            AsyncCallback rc = null;
            rc = readResult =>
            {
                try
                {
                    int read = source.EndRead(readResult);
                    if (read > 0)
                    {
                        destination.BeginWrite(buffer, 0, read, writeResult =>
                        {
                            try
                            {
                                destination.EndWrite(writeResult);
                                source.BeginRead(
                                    buffer, 0, buffer.Length, rc, null);
                            }
                            catch (Exception exc) { cbCompleted(exc); }
                        }, null);
                    }
                    else cbCompleted(null);
                }
                catch (Exception exc) { cbCompleted(exc); }
            };

            source.BeginRead(buffer, 0, buffer.Length, rc, null);
        }
Example #17
0
        void OnReadDone(IAsyncResult ar)
        {
            Enqueue(delegate {
                if (stream != null)
                {
                    int result = stream.EndRead(ar);

                    if (result > 0)
                    {
                        RaiseData(new ByteBuffer(readBuffer, 0, result));
                        ReadNextBuffer();
                    }
                    else
                    {
                        PauseReading();
                        RaiseEndOfStream();
                    }
                }
            });
        }
Example #18
0
        /// <summary>
        /// 异步创建文件
        /// </summary>
        public void CreateAsync(byte[] data, Action callback)
        {
            if (Exists)
            {
                throw new System.IO.IOException("file is exists");
            }

            data = Encrypted(data);

            System.IO.FileStream fs = System.IO.File.Create(FullName);
            //todo:需要测试
            fs.BeginWrite(data, 0, data.Length, (result) => {
                fs.EndRead(result);
                fs.Close();
                fs.Dispose();

                if (callback != null)
                {
                    callback.Invoke();
                }
            }, null);
        }
Example #19
0
        void OnReadDone(IAsyncResult ar)
        {
            Context.Enqueue(delegate {
                if (stream != null)
                {
                    ResetReadTimeout();
                    int result = stream.EndRead(ar);

                    if (result > 0)
                    {
                        byte [] newBuffer = new byte [result];
                        Buffer.BlockCopy(buffer, 0, newBuffer, 0, result);

                        RaiseData(new ByteBuffer(newBuffer));
                        DispatchRead();
                    }
                    else
                    {
                        PauseReading();
                        RaiseEndOfStream();
                    }
                }
            });
        }
Example #20
0
 // len, buf, err
 public static void read(FileStream fd, byte[] buffer, long offset, long length, Action<int, byte[], Exception> callback)
 {
     try
     {
         fd.BeginRead(buffer, (int)offset, (int)length, ar =>
         {
             try
             {
                 int len = fd.EndRead(ar);
                 Boundary.Instance.ExecuteOnTargetLoop( () => callback( len, buffer, null ));
             } catch (Exception e){
                 Boundary.Instance.ExecuteOnTargetLoop( () => callback( 0, buffer, null ));
             }
         }, null);
     }
     catch (Exception e)
     {
         callback(0, buffer, e);
     }
 }
        private void DoSequentialRead(
            BlobTransferContext transferContext,
            FileStream stream,
            byte[] streamBuffer = null,
            KeyValuePair<long, int>? inputStartAndLength = null)
        {
            if (transferContext.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (streamBuffer == null)
            {
                streamBuffer = transferContext.MemoryManager.RequireBuffer();
            }

            if (streamBuffer == null)
            {
                return;
            }

            KeyValuePair<long, int> startAndLength;

            if (inputStartAndLength == null)
            {
                if (!transferContext.BlocksToTransfer.TryDequeue(out startAndLength))
                {
                    transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
                    return;
                }
            }
            else
            {
                startAndLength = inputStartAndLength.Value;
            }
            // Catch any exceptions and cleanup the buffer. Otherwise uncleaned buffers will result in hang for future
            // uploads as memorymanager is being shared.
            // Also mark the transfer as complete and add exceptions to the transfercontext exception list.
            try
            {
                if (!transferContext.PartialFileIOState.ContainsKey(startAndLength.Key))
                {
                    transferContext.PartialFileIOState[startAndLength.Key] = 0;
                }

                transferContext.IsReadingOrWriting = true;

                long beginFilePosition = startAndLength.Key;
                long nextBeginFilePosition = startAndLength.Key + transferContext.BlockSize;

                nextBeginFilePosition =
                    nextBeginFilePosition > transferContext.Length
                        ? transferContext.Length
                        : nextBeginFilePosition;

                beginFilePosition = beginFilePosition + transferContext.PartialFileIOState[startAndLength.Key];
                int bytesToRead = (int)(nextBeginFilePosition - beginFilePosition);

                stream.BeginRead(
                    streamBuffer,
                    transferContext.PartialFileIOState[startAndLength.Key],
                    bytesToRead,
                    result3 =>
                    {
                        int bytesRead;

                        SuccessfulOrRetryableResult wasReadSuccessful =
                            IsActionSuccessfulOrRetryable(transferContext, () => stream.EndRead(result3), out bytesRead);

                        if (!wasReadSuccessful.IsSuccessful)
                        {
                            transferContext.IsReadingOrWriting = false;

                            transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
                        }
                        else if (bytesRead != bytesToRead)
                        {
                            transferContext.PartialFileIOState[startAndLength.Key] += bytesRead;

                            DoSequentialRead(transferContext, stream, streamBuffer, startAndLength);
                        }
                        else
                        {
                            transferContext.IsReadingOrWriting = false;

                            ApplyEncryptionTransform(
                                transferContext.FileEncryption,
                                Path.GetFileName(transferContext.LocalFilePath),
                                beginFilePosition,
                                streamBuffer,
                                bytesToRead);

                            transferContext.BlocksForFileIO[(int)(startAndLength.Key / transferContext.BlockSize)] = streamBuffer;
                        }
                    },
                    null);
            }
            catch (Exception ex)
            {
                transferContext.IsComplete = true;
                transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
                transferContext.Exceptions.Add(ex);
            }
        }
Example #22
0
        public void ProcessItems(string src, string dst)
        {
            int size = 2048 * 1024 * 2;  //buffer size
            int current_read_buffer = 0; //pointer to current read buffer
            int last_bytes_read     = 0; //number of bytes last read

            if (!Directory.Exists(System.IO.Path.GetDirectoryName(dst)))
            {
                Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dst));
            }

            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[size];
            buffer[1] = new byte[size];

            //Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
            //                (Action)(() =>
            //                {
            //                    lblFileName.Text = System.IO.Path.GetFileNameWithoutExtension(src);
            //                }));

            using (var r = new System.IO.FileStream(src, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite, size * 2, System.IO.FileOptions.SequentialScan | System.IO.FileOptions.Asynchronous))
            {
                //Microsoft.Win32.SafeHandles.SafeFileHandle hDst = CreateFile(dst, (uint)System.IO.FileAccess.Write, (uint)System.IO.FileShare.None, IntPtr.Zero, (uint)System.IO.FileMode.Create, FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_OVERLAPPED, IntPtr.Zero);
                var z = new FileStream(dst, FileMode.Create, FileAccess.Write, FileShare.None, size * 2,
                                       FileOptions.WriteThrough | FileFlagNoBuffering | FileOptions.SequentialScan);
                z.Close();
                z.Dispose();
                using (var w = new System.IO.FileStream(dst, FileMode.Open, System.IO.FileAccess.Write, FileShare.ReadWrite, size * 2, true))
                {
                    current_read_buffer = 0;
                    last_bytes_read     = r.Read(buffer[current_read_buffer], 0, size); //synchronously read the first buffer
                    long l = r.Length;
                    //w.SetLength(l);
                    long i = 0;
                    while (i < l)
                    {
                        _block.WaitOne();
                        if (Cancel)
                        {
                            Environment.Exit(5);
                            break;
                        }
                        IAsyncResult aw = w.BeginWrite(buffer[current_read_buffer], 0, last_bytes_read, new AsyncCallback(CopyFileCallback), 0);
                        current_read_buffer = current_read_buffer == 0 ? 1 : 0;
                        Thread.CurrentThread.Join(2);
                        IAsyncResult ar = r.BeginRead(buffer[current_read_buffer], 0, last_bytes_read, new AsyncCallback(CopyFileCallback), 0);
                        i += last_bytes_read;

                        if (i > 0)
                        {
                            long oldvalbefore = 0;
                            oldbyteVlaues.TryGetValue(src, out oldvalbefore);


                            long oldval = 0;
                            if (oldbyteVlaues.TryGetValue(src, out oldval))
                            {
                                oldbyteVlaues[src] = i;
                            }
                            else
                            {
                                oldbyteVlaues.Add(src, i);
                            }

                            if (i - oldvalbefore > 0)
                            {
                                totaltransfered += (i - oldvalbefore);
                            }

                            byte[] data = System.Text.Encoding.Unicode.GetBytes(String.Format("{0}|{1}|{2}|{3}", i, l, totaltransfered, src));
                            WindowsAPI.SendStringMessage(MessageReceiverHandle, data, 0, data.Length);
                            if (i == l)
                            {
                                //procCompleted++;
                                if (this.OPType == OperationType.Move)
                                {
                                    r.Close();
                                    r.Dispose();
                                    FileInfo fi = new FileInfo(src);
                                    if (fi.IsReadOnly)
                                    {
                                        fi.IsReadOnly = false;
                                    }
                                    fi.Delete();
                                }
                            }

                            //if (totaltransfered == total)
                            //{

                            //    if (this.OPType == OperationType.Move)
                            //    {
                            //        foreach (var dir in this.SourceItemsCollection.Select(c =>  ShellObject.FromParsingName(c.Item1)).ToArray().Where(c => c.IsFolder))
                            //        {
                            //            DeleteAllFilesFromDir(new DirectoryInfo(dir.ParsingName), false);
                            //            DeleteFolderRecursive(new DirectoryInfo(dir.ParsingName), false);
                            //        }
                            //        GC.WaitForPendingFinalizers();
                            //        GC.Collect();
                            //    }
                            //    Environment.Exit(5);

                            //}
                        }
                        else
                        {
                            //oldbyteVlaue = 0;
                            oldbyteVlaues[src] = 0;
                            if (l == 0)
                            {
                                Environment.Exit(5);
                            }
                        }

                        last_bytes_read = r.EndRead(ar);
                        Thread.Sleep(1);
                        w.EndWrite(aw);
                    }
                }
            }
        }
Example #23
0
            public void ThreadMethod()
            {
                threadId = Thread.CurrentThread.ManagedThreadId;

                try
                {
                    // Signal the openning thread that we're up and running.
                    if (ThreadStarted != null)
                        ThreadStarted.Set();

                    using (FileStream fs = new FileStream(HidHandle, FileAccess.Read, InputReportByteLength, true))
                    {
                        byte[] buffer = new byte[InputReportByteLength];

                        while (true)
                        {
                           IAsyncResult res = fs.BeginRead(buffer, 0, InputReportByteLength, AsyncCallback, null);

                            // We need to wait for either IO to complete or the read to be signaled
                            WaitHandle[] IOCompleteOrThreadTerminating = { res.AsyncWaitHandle, ThreadTerminating };

                            // Wait for data or thread termination
                            if (1 == WaitHandle.WaitAny(IOCompleteOrThreadTerminating))
                                break;

                            
                            // Call endRead to get the # of bytes actually read.  This will throw an exception
                            // if the read was not successfull (i.e. the device was removed, etc).
                            int bytesRead = fs.EndRead(res);
                            Logger.Info(devicename, "read " + bytesRead.ToString(CultureInfo.InvariantCulture) + " bytes from device.");

                            // Make sure we got the correct # of bytes
                            if (bytesRead == InputReportByteLength)
                            {
                                // Get strong ref to callback delegate
                                DataReadCallback callback = wdcallback.Target as DataReadCallback;
                                if (callback == null)
                                    break;
                                
                                // report data to caller
                                callback(buffer);

                                callback = null;
                            }
                            else
                            {
                                // Unexpected data size - we'll thrown an exception for now.
                                // This may need to change for devices that report variable length data.
                                throw new PosControlException(rm.GetString("IDS_UNEXPECTED_NUMBER_BYTES"), ErrorCode.Failure);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    // We must eat this exception and marshal it back to the calling thread or else the 
                    // CLR will terminate the process
                    Logger.Error(devicename, "Exception occurred in HID read thread.", e);

					//if (e.Message.CompareTo("The device is not connected.\r\n") == 0)
					if (e is IOException)
					{
						lock (syncRoot)
						{
							if (null != HidHandle)
							{
								if (!HidHandle.IsClosed)
									HidHandle.Close();
								HidHandle.Dispose();
								HidHandle = null;
							}
						}
					}
					ThreadExceptionCallback excallback = wdexcallback.Target as ThreadExceptionCallback;
                    if (excallback != null)
                        excallback(e);  // report exception to caller
					excallback=null;
                }
            }
Example #24
0
        public override IEnumerator<CoroutineState> GetEnumerator()
        {
            FileStream fileReader = new FileStream(
                _fileName,
                 FileMode.Open,
                 FileAccess.Read,
                 FileShare.Read,
                 BUFFER_SIZE,
                 true);

            FileStream fileWriter = new FileStream(
                Path.Combine(_destinationFolder, Path.GetFileName(_fileName)),
                FileMode.Create,
                FileAccess.ReadWrite,
                FileShare.Write,
                BUFFER_SIZE,
                true);

            int bytesRead = 0;

            do
            {
                //Read asynchronously
                bool finishedRead = false;
                IAsyncResult readResult = fileReader.BeginRead(_buffer, 0, BUFFER_SIZE,
                    (asyncResult) =>
                    {
                        bytesRead = fileReader.EndRead(asyncResult);
                        finishedRead = true;
                    },
                    null);

                //Wait until the reading is complete
                while (!finishedRead)
                {
                    //Allow other coroutines to run
                    yield return CoroutineState.Running;
                }
                Console.WriteLine("Finished reading chunk for: " + _fileName);

                //Write asynchronously
                bool finishedWriting = false;
                IAsyncResult writeResult = fileWriter.BeginWrite(_buffer, 0, bytesRead,
                    (asyncResult) =>
                    {
                        fileWriter.EndWrite(asyncResult);
                        finishedWriting = true;
                    },
                    null);

                //Wait until write is finished
                while (!finishedWriting)
                {
                    //Let other coroutines run
                    yield return CoroutineState.Running;
                }
                Console.WriteLine("Finished writing chunk for: " + _fileName);

            } while (bytesRead > 0);

            fileReader.Close();
            fileWriter.Close();
        }
        private void DoSequentialRead(
            BlobTransferContext transferContext,
            FileStream stream,
            byte[] streamBuffer = null,
            KeyValuePair<long, int>? inputStartAndLength = null)
        {
            if (transferContext.CancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (streamBuffer == null)
            {
                streamBuffer = transferContext.MemoryManager.RequireBuffer();
            }

            if (streamBuffer == null)
            {
                return;
            }

            KeyValuePair<long, int> startAndLength;

            if (inputStartAndLength == null)
            {
                if (!transferContext.BlocksToTransfer.TryDequeue(out startAndLength))
                {
                    transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
                    return;
                }
            }
            else
            {
                startAndLength = inputStartAndLength.Value;
            }

            if (!transferContext.PartialFileIOState.ContainsKey(startAndLength.Key))
            {
                transferContext.PartialFileIOState[startAndLength.Key] = 0;
            }

            transferContext.IsReadingOrWriting = true;

            long beginFilePosition = startAndLength.Key;
            long nextBeginFilePosition = startAndLength.Key + transferContext.BlockSize;

            nextBeginFilePosition =
                nextBeginFilePosition > transferContext.Length
                    ? transferContext.Length
                    : nextBeginFilePosition;

            beginFilePosition = beginFilePosition + transferContext.PartialFileIOState[startAndLength.Key];
            int bytesToRead = (int)(nextBeginFilePosition - beginFilePosition);

            stream.BeginRead(
                streamBuffer,
                transferContext.PartialFileIOState[startAndLength.Key],
                bytesToRead,
                result3 =>
                    {
                        int bytesRead;

                        SuccessfulOrRetryableResult wasReadSuccessful =
                            IsActionSuccessfulOrRetryable(transferContext, () => stream.EndRead(result3), out bytesRead);

                        if (!wasReadSuccessful.IsSuccessful)
                        {
                            transferContext.IsReadingOrWriting = false;

                            transferContext.MemoryManager.ReleaseBuffer(streamBuffer);
                        }
                        else if (bytesRead != bytesToRead)
                        {
                            transferContext.PartialFileIOState[startAndLength.Key] += bytesRead;

                            DoSequentialRead(transferContext, stream, streamBuffer, startAndLength);
                        }
                        else
                        {
                            transferContext.IsReadingOrWriting = false;

                            ApplyEncryptionTransform(
                                transferContext.FileEncryption,
                                Path.GetFileName(transferContext.LocalFilePath),
                                beginFilePosition,
                                streamBuffer,
                                bytesToRead);

                            transferContext.BlocksForFileIO[(int) (startAndLength.Key/transferContext.BlockSize)] = streamBuffer;
                        }
                    },
                null);
        }
Example #26
0
        // metoda, ktora de-facto implementuje maszyne stanowa pozwalajaca na asynchroniczny
        // odczyt pliku w obrebie jednej metody z zachowaniem wszystkich udogodnien jezyka!
        static IEnumerator<int> ReadFileOperation(AsyncController ctrl)
        {
            // otworz plik - dyrektywa USING!!
            using (var fs = new FileStream("Content.txt",
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                512,
                // otworz plik w trybie asynchronicznym!
                FileOptions.Asynchronous))
            {

                byte[] buffer = new byte[fs.Length];
                // rozpocznij odczyt
                // UWAGA - parametr callback odnosi sie do metody w kontrolerze maszyny stanowej
                IAsyncResult ar = fs.BeginRead(
                    buffer,
                    0,
                    buffer.Length,
                    ctrl.AsyncOperationCompleted,
                    null);

                Console.WriteLine("Starting async operation on thread: "
                    + Thread.CurrentThread.ManagedThreadId);

                // zwroc kontrole do kontrollera maszyny stanowej - wykonanie kodu jest przerwane!
                yield return 1;

                // ta linia kodu jest wykonywana po zakonczeniu odczytu - kontroller
                // maszyny stanowej wznawia iteracje!
                int bytesRead = fs.EndRead(ar);

                // odczyt danych
                using (var ms = new MemoryStream(buffer))
                using (var str = new StreamReader(ms))
                {
                    string fileName = null;

                    // odczyt danych z pilku - linia po linii
                    while (!string.IsNullOrEmpty(fileName = str.ReadLine()))
                    {
                        // dla każdej linii - sprobuj otworzy nowy plik
                        using (var contentFs = new FileStream(
                            fileName,
                            FileMode.Open,
                            FileAccess.Read,
                            FileShare.Read,
                            512,
                            // otworz plik w trybie asynchronicznym!
                            FileOptions.Asynchronous))
                        {
                            buffer = new byte[contentFs.Length];
                            // rozpocznij odczyt z pliku
                            IAsyncResult contentAr = contentFs.BeginRead(
                                buffer,
                                0,
                                buffer.Length,
                                ctrl.AsyncOperationCompleted,
                                null);

                            // poczekaj az dane zostana odczytane
                            yield return 1;

                            contentFs.EndRead(contentAr);

                            // i wyswietl je na konsole
                            using (var contentMs = new MemoryStream(buffer))
                            using (var contentStr = new StreamReader(contentMs))
                            {
                                Console.Write(contentStr.ReadToEnd());
                            }
                        }
                    }

                    Console.WriteLine("Read Completed on thread " +
                        Thread.CurrentThread.ManagedThreadId);

                }
                // zakonczenie przetwarzania - nie ma wiecej operacji do wykonania!
            }
        }
Example #27
0
 // cannot return String from this method
 private void RestoreInput()
 {
     var stream = new FileStream(
         "savedInput.txt",
         FileMode.OpenOrCreate,
         FileAccess.Read,
         FileShare.Read,
         bufferSize: 8192,
         useAsync: true);
     var buffer = new byte[stream.Length];
     var context = SynchronizationContext.Current;
     stream.BeginRead(buffer, 0, buffer.Length, asyncResult =>
         {
             Thread.Sleep(TimeSpan.FromSeconds(2));
             context.Post(_ =>
                 {
                     try
                     {
                         stream.EndRead(asyncResult);
                         stream.Dispose();
                         Input = Encoding.ASCII.GetString(buffer);
                     }
                     catch
                     {
                         Input = "Error!!!";
                     }
                     finally
                     {
                         DisplayLoadCompletedNotification();
                     }
                 }, null);
         },
         null);
 }
        /// <summary>
        /// Copies the specified source file to the specified destination file, overwriting if it exists.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="destination">The destination.</param>
        public static void Copy(string source, string destination)
        {
            var bufferLength = 4 * 1024 * 32;
            var readBuffer = new Byte[bufferLength];
            var writeBuffer = new Byte[bufferLength];
            var readSize = -1;

            IAsyncResult writeResult;
            IAsyncResult readResult;

            using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
            using (var destinationStream = new FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 8, FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                destinationStream.SetLength(sourceStream.Length);
                readSize = sourceStream.Read(readBuffer, 0, readBuffer.Length);
                readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);

                while (readSize > 0)
                {
                    writeResult = destinationStream.BeginWrite(writeBuffer, 0, readSize, null, null);
                    readResult = sourceStream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
                    destinationStream.EndWrite(writeResult);
                    readSize = sourceStream.EndRead(readResult);
                    readBuffer = Interlocked.Exchange(ref writeBuffer, readBuffer);
                }

                sourceStream.Close();
                destinationStream.Close();
            }
        }
Example #29
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(tempStream.EndRead(asyncResult));
 }
 //使用FileStream对象的BeginRead()方法
 void AsyncRead()
 {
     FileStream fs = new FileStream(Server.MapPath("/UTF8Text.txt"), FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.Asynchronous);
     fs.Seek(0, SeekOrigin.Begin);
     byte[] buffer = new byte[100];
     //开始异步读操作
     IAsyncResult ar = fs.BeginRead(buffer, 0, buffer.Length, null, null);
     while (!ar.AsyncWaitHandle.WaitOne(10, false))//直到异步读文件操作完成才退出轮询
     {
     }
     int bytesRead = fs.EndRead(ar);//结束异步读操作
     fs.Close();
     string str = Encoding.Default.GetString(buffer, 0, buffer.Length);
     Response.Write(str);
 }
		public void BeginRead_Disposed () 
		{
			string path = TempFolder + Path.DirectorySeparatorChar + "temp";
			DeleteFile (path);
			FileStream stream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Read);
			stream.Close ();
			stream.EndRead (stream.BeginRead (new byte[8], 0, 8, null, null));
		}
Example #32
0
        internal UInt64 ExtendFile(UInt64 fp, string filename)
        {
            int size = 65536 * 4;
            byte[] readBuf = new byte[size];
            byte[] fpBuf = new byte[size];

            ulong fileFP = fp;
            using (Stream ifs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, size, FileOptions.Asynchronous | FileOptions.SequentialScan))
            {
                IAsyncResult readResult = ifs.BeginRead(readBuf, 0, readBuf.Length, null, null);
                while (true)
                {
                    int bytesRead = ifs.EndRead(readResult);
                    if (bytesRead == 0) break;

                    byte[] tmpBuf = fpBuf;
                    fpBuf = readBuf;
                    readBuf = tmpBuf;
                    readResult = ifs.BeginRead(readBuf, 0, readBuf.Length, null, null);
                    fileFP = this.Extend(fileFP, fpBuf, 0, bytesRead);
                }
            }
            return fileFP;
        }
Example #33
0
        private static void SampleAsyncMethods()
        {
            IAsyncResult asyncResult;

            /***** SQL Connection *****/
            // NOTE: "Async=true" setting required for asynchronous operations.
            using (SqlConnection connection = new SqlConnection(@"Async=true;Server=SERVER;Database=DATABASE;Integrated Security=true"))
            {
                connection.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT UserId, Name, LastLogIn FROM Users WHERE Email = '*****@*****.**'", connection))
                {
                    asyncResult = cmd.BeginExecuteReader();
                    // ... query executes asynchronously in background ...
                    using (IDataReader reader = cmd.EndExecuteReader(asyncResult))
                    {
                        // WARNING: The DbAsyncResult object returned by BeginExecuteReader always creates a ManualResetEvent, but
                        // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                        asyncResult.AsyncWaitHandle.Close();

                        while (reader.Read())
                        {
                            // do stuff
                        }
                    }
                }

                using (SqlCommand cmd = new SqlCommand("UPDATE Users SET LastLogIn = GETUTCDATE() WHERE UserId = 1", connection))
                {
                    asyncResult = cmd.BeginExecuteNonQuery();
                    // ... query executes asynchronously in background ...
                    int rowsAffected = cmd.EndExecuteNonQuery(asyncResult);

                    // WARNING: The DbAsyncResult object returned by BeginExecuteNonQuery always creates a ManualResetEvent, but
                    // never closes it; after calling EndExecuteReader, the AsyncWaitHandle property is still valid, so we close it explicitly.
                    asyncResult.AsyncWaitHandle.Close();
                }
            }

            /***** File Operations *****/
            // NOTE: FileOptions.Asynchronous flag required for asynchronous operations.
            using (Stream stream = new FileStream(@"C:\Temp\test.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096,
                FileOptions.Asynchronous))
            {
                byte[] buffer = new byte[65536];
                asyncResult = stream.BeginRead(buffer, 0, buffer.Length, null, null);
                // ... disk read executes asynchronously in background ...
                int bytesRead = stream.EndRead(asyncResult);
            }

            /***** HTTP Operation *****/
            // WARNING: DNS operations are synchronous, and will block!
            WebRequest request = WebRequest.Create(new Uri(@"http://www.example.com/sample/page"));
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            asyncResult = request.BeginGetRequestStream(null, null);
            // ... connection to server opened in background ...
            using (Stream stream = request.EndGetRequestStream(asyncResult))
            {
                byte[] bytes = Encoding.UTF8.GetBytes("Sample request");
                asyncResult = stream.BeginWrite(bytes, 0, bytes.Length, null, null);
                stream.EndWrite(asyncResult);
            }

            // WARNING: WebRequest will swallow any exceptions thrown from the AsyncCallback passed to BeginGetResponse.
            asyncResult = request.BeginGetResponse(null, null);
            // ... web request executes in background ...
            using (WebResponse response = request.EndGetResponse(asyncResult))
            using (Stream stream = response.GetResponseStream())
            {
                // read response from server
                // WARNING: This code should also use asynchronous operations (BeginRead, EndRead); "Using synchronous calls
                //   in asynchronous callback methods can result in severe performance penalties." (MSDN)
            }

            /***** DNS hostname resolution *****/
            // WARNING: Doesn't truly use async I/O, but simply queues the request to a ThreadPool thread.
            asyncResult = Dns.BeginGetHostEntry("www.example.com", null, null);
            // ... DNS lookup executes in background
            IPHostEntry entry = Dns.EndGetHostEntry(asyncResult);

            /***** Other: Sockets, Serial Ports, SslStream *****/
        }
Example #34
0
        public static void LoadFile(string path, Action<string, Stream> onSuccessfulLoad, TextWriter errorOut)
        {
            const string ioExceptionPreamble = "Could not read program file due to an IO Exception.";
            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, fileBufferSize, true);
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                errorOut.WriteLine("Could not read program file." + fileNotFoundException.Message);
                return;
            }
            catch (IOException ioException)
            {
                errorOut.Write(ioExceptionPreamble + ioException.Message);
                return;
            }

            LoadState loadState = new LoadState(fileBufferSize);
            int bytesRead = -1;
            Func<bool> iterate = null;
            AsyncCallback onEndRead = null;
            Action onLoadComplete = null;

            iterate = () =>
            {
                while (bytesRead != 0)
                {
                    IAsyncResult result = fileStream.BeginRead(loadState.ReadBuffer, 0, fileBufferSize, onEndRead, null);
                    if (!result.CompletedSynchronously)
                    {
                        return false;
                    }
                    bytesRead = fileStream.EndRead(result);
                    loadState.FlushReadBuffer(bytesRead);
                }
                return true;
            };

            onEndRead = (ar) =>
            {
                if (!ar.CompletedSynchronously)
                {
                    try
                    {
                        bytesRead = fileStream.EndRead(ar);
                        loadState.FlushReadBuffer(bytesRead);
                        if (iterate())
                        {
                            onLoadComplete();
                        }
                    }
                    catch (IOException ioException)
                    {
                        errorOut.Write(ioExceptionPreamble + ioException.Message);
                        fileStream.Close();
                    }
                    catch
                    {
                        fileStream.Close();
                        throw;
                    }
                }
            };

            onLoadComplete = () =>
            {
                fileStream.Close();
                loadState.BufferedFile.Seek(0, SeekOrigin.Begin);
                onSuccessfulLoad(path, loadState.BufferedFile);
            };

            try
            {
                if (iterate())
                {
                    onLoadComplete();
                }
            }
            catch (IOException ioException)
            {
                errorOut.Write(ioExceptionPreamble + ioException.Message);
                fileStream.Close();
            }
            catch
            {
                fileStream.Close();
                throw;
            }
        }