Created
July 14, 2015 15:18
-
-
Save Fhernd/31e1324fc43fa70812b7 to your computer and use it in GitHub Desktop.
Procesador de lectura asincrónica en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
using System.Threading; | |
namespace Receta.CSharp.R0509 | |
{ | |
public class ProcesadorLecturaAsincronica | |
{ | |
private Stream inputStream; | |
// Tamaño del búfer para lectura por bloques (2KB): | |
private int tamanioBufer = 2048; | |
// Obtiene y establece el tamaño del búfer: | |
public int TamanioBufer | |
{ | |
get | |
{ | |
return tamanioBufer; | |
} | |
set | |
{ | |
tamanioBufer = value; | |
} | |
} | |
// Búfer de almacenamiento de datos leídos: | |
private byte[] bufer; | |
public ProcesadorLecturaAsincronica(string nombreArchivo) | |
{ | |
bufer = new byte[tamanioBufer]; | |
// Apertura de archivo con lectura asincrónica (true): | |
inputStream = new FileStream(nombreArchivo, FileMode.Open, | |
FileAccess.Read, FileShare.Read, | |
tamanioBufer, true); | |
} | |
// Inicia el proceso de lectura asincrónica: | |
public void IniciarLectura() | |
{ | |
inputStream.BeginRead(bufer, 0, bufer.Length, | |
OnLecturaFinalizada, null); | |
} | |
// Callback una vez finalizada la lectura: | |
private void OnLecturaFinalizada(IAsyncResult asyncResult) | |
{ | |
int bytesLeidos = inputStream.EndRead(asyncResult); | |
// Aún restan bytes por leer: | |
if (bytesLeidos > 0) | |
{ | |
// Simulación de operación de lectura larga: | |
Console.WriteLine("\t[PROCESAOR ASINCRÓNICO]: Lectura de un bloque de datos."); | |
Thread.Sleep(TimeSpan.FromMilliseconds(20)); | |
// Inicio de la lectura del siguiente bloque de forma asincrónica: | |
inputStream.BeginRead(bufer, 0, bufer.Length, OnLecturaFinalizada, null); | |
} | |
else | |
{ | |
// Fin del procesamiento> | |
Console.WriteLine("\t[PROCESAOR ASINCRÓNICO]: Operación finalizada."); | |
inputStream.Close(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment