Advertisement
Fhernd

ProcesadorLecturaAsincronica.cs

Jul 19th, 2015
997
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.36 KB | None | 0 0
  1. // OrtizOL - xCSw - http://ortizol.blogspot.com
  2.  
  3. using System;
  4. using System.IO;
  5. using System.Threading;
  6.  
  7. namespace Receta.Multithreading.R0301
  8. {
  9.     public class ProcesadorLecturaAsincronica
  10.     {
  11.         private Stream inputStream;
  12.        
  13.         // Tamaño del búfer para lectura por bloques (2KB):
  14.         private int tamanioBufer = 2048;
  15.        
  16.         // Obtiene y establece el tamaño del búfer:
  17.         public int TamanioBufer
  18.         {
  19.             get
  20.             {
  21.                 return tamanioBufer;
  22.             }
  23.             set
  24.             {
  25.                 tamanioBufer = value;
  26.             }
  27.         }
  28.        
  29.         // Búfer de almacenamiento de datos leídos:
  30.         private byte[] bufer;
  31.        
  32.         public ProcesadorLecturaAsincronica(string nombreArchivo)
  33.         {
  34.             bufer = new byte[tamanioBufer];
  35.            
  36.             // Apertura de archivo con lectura asincrónica (true):
  37.             inputStream = new FileStream(nombreArchivo, FileMode.Open,
  38.                                          FileAccess.Read, FileShare.Read,
  39.                                          tamanioBufer, true);
  40.         }
  41.        
  42.         // Inicia el proceso de lectura asincrónica:
  43.         public void IniciarLectura()
  44.         {
  45.             inputStream.BeginRead(bufer, 0, bufer.Length,
  46.                                   OnLecturaFinalizada, null);
  47.         }
  48.        
  49.         // Callback una vez finalizada la lectura:
  50.         private void OnLecturaFinalizada(IAsyncResult asyncResult)
  51.         {
  52.             int bytesLeidos = inputStream.EndRead(asyncResult);
  53.            
  54.             // Aún restan bytes por leer:
  55.             if (bytesLeidos > 0)
  56.             {
  57.                 // Simulación de operación de lectura larga:
  58.                 Console.WriteLine("\t[PROCESADOR ASINCRÓNICO]: Lectura de un bloque de datos.");
  59.                 Thread.Sleep(TimeSpan.FromMilliseconds(20));
  60.                
  61.                 // Inicio de la lectura del siguiente bloque de forma asincrónica:
  62.                 inputStream.BeginRead(bufer, 0, bufer.Length, OnLecturaFinalizada, null);
  63.             }
  64.             else
  65.             {
  66.                 // Fin del procesamiento>
  67.                 Console.WriteLine("\t[PROCESAOR ASINCRÓNICO]: Operación finalizada.");
  68.                 inputStream.Close();
  69.             }
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement