Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 19, 2015 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/9a4aff609fa94b0dd8a4 to your computer and use it in GitHub Desktop.
Save Fhernd/9a4aff609fa94b0dd8a4 to your computer and use it in GitHub Desktop.
Procesador de lectura asincrónica en C#.
// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.IO;
using System.Threading;
namespace Receta.Multithreading.R0301
{
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[PROCESADOR 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