BeginRead() public method

public BeginRead ( byte array, int offset, int numBytes, AsyncCallback callback, object state ) : IAsyncResult
array byte
offset int
numBytes int
callback AsyncCallback
state object
return IAsyncResult
Example #1
1
 public void BeginReadThrowsForWriteOnly()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<NotSupportedException>(() => fs.BeginRead(new byte[0], 0, 0, null, null));
     }
 }
Example #2
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 #3
0
 public void BeginReadThrowsForBadOffset(int arraySize, int offset, int numBytes)
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentException>(() => fs.BeginRead(new byte[arraySize], offset, numBytes, null, null));
     }
 }
Example #4
0
 public void BeginReadThrowsForNullArray()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentNullException>("array", () => fs.BeginRead(null, 0, 0, null, null));
     }
 }
Example #5
0
 public void BeginReadThrowsForNegativeNumBytes()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentOutOfRangeException>("numBytes", () => fs.BeginRead(new byte[0], 0, -1, null, null));
     }
 }
Example #6
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();
 }
        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 #8
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();
        }
Example #9
0
        public void DownFile(string fileName)
        {
            var callback = OperationContext.Current.GetCallbackChannel<IMediaCallBack>();
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var customFile = new CustomFile(callback, fs, fileName);

            fs.BeginRead(customFile.CurrentByte, 0, customFile.MaxLength, DownFileCallBack, customFile);
        }
Example #10
0
        public void BeginReadThrowsForClosed()
        {
            FileStream fs;
            using (fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
            }

            Assert.Throws<ObjectDisposedException>(() => fs.BeginRead(new byte[0], 0, 0, null, null));
        }
Example #11
0
 public static void Load(string fileName)
 {
     startTime = DateTime.Now;
     Loaded = 0;
     FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     Size = (int)fs.Length;
     FileData = new byte[Size];
     fs.BeginRead(FileData, 0, Size, new AsyncCallback(read), fs);
 }
Example #12
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 #13
0
 static void Main(string[] args)
 {
     const string FilePath = @"D:\Downloads\Sygic 13.2.2\Sygic Map Downloader (TomTom 2013.06)\sgcmapdownloader.txt";
     FileStream fileStream = new FileStream(FilePath,
     FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
     FileOptions.Asynchronous);
     IAsyncResult result = fileStream.BeginRead(buffer, 0, buffer.Length, 
         new AsyncCallback(CompleteRead), fileStream);
     Console.ReadLine();
 }
 private void ReplaceFileContent(string file)
 {
     var fileStream = new FileStream(file, FileMode.Open);
     var state = new FileState
     {
         FileStream = fileStream,
         FileName = file,
         Data = new byte[fileStream.Length]
     };
     fileStream.BeginRead(state.Data, 0, (int)fileStream.Length, ReadDone, state);
 }
        public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) {

            HttpRequest request = context.Request;
            m_response = context.Response;

            lock (m_lock) {
                m_fileStream = new FileStream(request.MapPath("~/App_Data/TrackerLog.xml"), FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
                m_xmlFragmentByteArray = new byte[m_fileStream.Length];
                return m_fileStream.BeginRead(m_xmlFragmentByteArray, 0, (int)m_fileStream.Length, cb, extraData);
            }
        }
Example #16
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 #17
0
        private static void AsyncReadOneFileCallBack()
        {
            Console.WriteLine("Основной поток ID = {0}",
               Thread.CurrentThread.ManagedThreadId);

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

            fs.BeginRead(staticData, 0, staticData.Length, ReadIsComplete, fs);
            Console.ReadLine();
        }
Example #18
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);
        }
        static void Main(string[] args) {

            const string filePath = @"C:\Apps\Foo.txt";

            FileStream fileStream = new FileStream(filePath,
                FileMode.Open, FileAccess.Read, FileShare.Read, 1024,
                FileOptions.Asynchronous);

            IAsyncResult result = fileStream.BeginRead(buffer, 0, buffer.Length,
                    new AsyncCallback(CompleteRead), fileStream);

            Console.ReadLine();
        }
Example #20
0
 public void BeginLoad()
 {
     string path = _uri.PathAndQuery;
     FileInfo fi = new FileInfo(path);
     if(fi.Exists)
     {
         FileStream fs = new FileStream(path, FileMode.Open);
         // Create a synchronization object that gets
         // signaled when read is complete.
         ManualResetEvent manualEvent = new ManualResetEvent(false);
         var stateObject = new State(fs, fi.Length, manualEvent);
         //todo: implement buffer of 4096 size and provide intermediate state notifications
         fs.BeginRead(stateObject.Buffer, 0, (int)stateObject.BufferSize, new AsyncCallback(EndReadCallback), stateObject);
     }
 }
        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);

            // initiate asynchronous read operation, reading first 100 bytes
            // pass filestream object (fs) to callback
            fs.BeginRead(data, 0, data.Length, ReadIsDone, fs);

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

            Console.ReadKey();
        }
Example #22
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 #23
0
        static void Main(string[] args)
        {
            //sync
            var syncStream = new FileStream("file.txt", FileMode.Open);
            var syncBuffer = new byte[1024];
            var syncBytesRead = syncStream.Read(syncBuffer, 0, syncBuffer.Length);
            Console.WriteLine("Read " + syncBytesRead + " bytes syncronously");
            syncStream.Close();

            //Async Programming Model
            stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
            buffer = new byte[1024];
            var asyncResult = stream.BeginRead(buffer, 0, buffer.Length, FinishedRead, null);
            //can also poll for status
            while(!asyncResult.IsCompleted)
            {
                Console.WriteLine("Waiting for BeginRead to complete");
            }
            stream.Close();

            //Event-based Async Pattern
            var client = new WebClient();
            client.DownloadStringCompleted += ClientOnDownloadStringCompleted;
            client.DownloadStringAsync(new Uri("http://www.rtigger.com"));
            
            while(string.IsNullOrEmpty(downloadedString))
            {
                Console.WriteLine("Waiting for DownloadString to complete");
                Thread.Sleep(100);
            }
            
            //Task Async Pattern
            var stream2 = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
            var buffer2 = new byte[1024];
            var result = Task<int>.Factory.FromAsync(stream2.BeginRead, stream2.EndRead, buffer2, 0, buffer2.Length, null);
            //do other things while task is executing
            while(!result.IsCompleted)
            {
                Console.WriteLine("Waiting for Task to complete");
            }
            Console.WriteLine("Task finished, read " + result.Result + " bytes from file");

            //async pattern
            AsyncContext.Run(() => DownloadStringAsync("http://www.rtigger.com"));

            Console.ReadLine();
        }
Example #24
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 #25
0
        public static string AsyncRead(string filePath)
        {
            // string filePath = "c:\\test.txt";
            //以只读方式打开文件流
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.Asynchronous))
            {
                var buffer = new byte[bufferSize];

                //构造BeginRead需要传递的状态
                AsyncState asyncState = new AsyncState() { FS = fileStream, Buffer = buffer, WaitHandle = new ManualResetEvent(false) };
                asyncState.Rs = new List<byte>();

                //异步读取
                IAsyncResult asyncResult = fileStream.BeginRead(buffer, 0, bufferSize, new AsyncCallback(AsyncReadCallback), asyncState);
                asyncState.WaitHandle.WaitOne();
                //Console.WriteLine("read complete");
                return Encoding.UTF8.GetString(asyncState.Rs.ToArray());
            }
        }
Example #26
0
        static void Main(string[] args)
        {
            Callback = new AsyncCallback(CallBackFunction);

            fileStm = new FileStream("C:\\Users\\admin\\Documents\\Visual Studio 2013\\Projects\\network_programming_for_professionals\\bin\\Debug\\SyncDemo.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 64, true);
            readbuf = new byte[fileStm.Length];
            fileStm.BeginRead(readbuf, 0, readbuf.Length, Callback, null);

            for(long i=0;i<5000;i++)
            {
                if(i%1000==0)
                {
                    Console.WriteLine("Executing in Main -" + i.ToString());
                    Thread.Sleep(1000);
                }
            }
            fileStm.Close();

            Console.ReadKey();
        }
Example #27
0
        static void Main(string[] args)
        {
            // otworz plik
            var fs = new FileStream("Content.txt",
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                512,
                // otworz plik w trybie asynchronicznym!
                FileOptions.Asynchronous);

            buffer = new byte[fs.Length];
            // rozpocznij odczyt
            // UWAGA: ostatni element, stan - przekazuje referencje do strumienia!
            fs.BeginRead(buffer, 0, buffer.Length, CompleteRead, fs);

            // zablokujmy glowny watek
            Console.WriteLine("waiting for complete read... thread: " +
                Thread.CurrentThread.ManagedThreadId);
            Console.ReadKey();
        }
Example #28
0
        public static void Main(string[] args)
        {
            //sync
            stream = new FileStream("file.txt", FileMode.Open);
            var buffer = new byte[1024];
            var bytesRead = stream.Read(buffer, 0, buffer.Length);
            Console.WriteLine("Read " + bytesRead + " from file");
            stream.Close();

            //APM
            stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
            var asyncResult = stream.BeginRead(buffer, 0, buffer.Length, FinishedRead, null);
            while (!asyncResult.IsCompleted)
            {
                Console.WriteLine("Waiting for begin read to finish");
            }

            //EAP
            var client = new WebClient();
            client.DownloadStringCompleted += OnDownloadStringCompleted;
            client.DownloadStringAsync(new Uri("http://rtigger.com"));
            while (string.IsNullOrEmpty(downloadedString))
            {
                Console.WriteLine("Waiting for download string to finish");
            }

            //task
            stream = new FileStream("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, true);
            var task = Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
            while (!task.IsCompleted)
            {
                Console.WriteLine("Waiting for task to finish");
            }            
            Console.WriteLine("Task is finished, read " + task.Result + " bytes from file");

            AsyncContext.Run(() => DownloadStringAsync("http://www.rtigger.com"));
            
            Console.ReadLine();
        }
Example #29
0
        public static string AsyncReadFile(string filePath, Encoding encoding)
        {
            if (IsExistFile(filePath))
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    int bufferSize = 1024;
                    byte[] data = new byte[bufferSize];
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 20480, true);//设置异步调用true
                    AsyncCallback callback = null;
                    callback = asyncResult =>
                    {
                        FileStream read = (FileStream)asyncResult.AsyncState;
                        int bytes=read.EndRead(asyncResult);
                        sb.Append(encoding.GetString(data,0,bytes));//Encoding.ASCII.GetString(data,0,bytes)
                        //System.Threading.Thread.Sleep(2000);
                        if (bytes > 0)
                        {
                            read.BeginRead(data, 0, bufferSize, callback, read);
                        }
                        else
                        {
                            read.Close(); Console.WriteLine(sb.ToString());
                        }
                    };

                    IAsyncResult async=fs.BeginRead(data, 0, bufferSize, callback, fs);
                    return sb.ToString();
                }
                catch (Exception ex)
                {
                    CooperationWrapper.WriteLog(ex);
                }
            }
            throw new FileNotFoundException("file not found");
        }
Example #30
0
        public void Run()
        {
            this.output.WriteLine("Thread APM start");
            this.CheckFileExists();

            var f = new FileInfo(this.sampleLogFileName);
            this.fileSizeInBytes = f.Length;
            this.lineSizeInBytesSoFar = 0;
            this.lineCount = 0;

            const int Chunksize = 4096;
            var buffer = new byte[Chunksize];

            var sw = new Stopwatch();
            sw.Start();

            var fs = new FileStream(
                this.sampleLogFileName,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                Chunksize,
                FileOptions.Asynchronous);

            fs.BeginRead(buffer, 0, buffer.Length, this.ReadAsyncCallback, new AsyncFileReadInfo(buffer, fs));

            this.output.WriteLine();
            this.output.WriteLine("All threads started, waiting to complete");
            WaitHandle.WaitOne();

            sw.Stop();
            this.ShowResults();

            this.output.WriteLine();
            this.output.WriteLine("Thread APM done in {0}", sw.Elapsed);
        }