Skip to content

Instantly share code, notes, and snippets.

@dschenkelman
Created May 9, 2014 04:35
Show Gist options
  • Save dschenkelman/e0f78a13a9298120efd0 to your computer and use it in GitHub Desktop.
Save dschenkelman/e0f78a13a9298120efd0 to your computer and use it in GitHub Desktop.
Asynchronous I/O in C#: Introduction
static void Main()
{
var fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
var buffer = new byte[1024];
fs.BeginRead(buffer, 0, 1024, ReadCallback, new State { Buffer = buffer, FileStream = fs });
Console.ReadLine();
}
private static void ReadCallback(IAsyncResult ar)
{
var state = (State)ar.AsyncState;
var bytesRead = state.FileStream.EndRead(ar);
Console.WriteLine(Encoding.UTF8.GetString(state.Buffer, 0, bytesRead));
state.FileStream.Close();
}
private class State
{
public FileStream FileStream { get; set; }
public byte[] Buffer { get; set; }
}
static async void ReadFromFile()
{
using (var fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read))
{
var buffer = new byte[1024];
var bytesRead = await fs.ReadAsync(buffer, 0, 1024);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));
}
Console.ReadLine();
}
static void Main()
{
using (var fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read))
{
var buffer = new byte[1024];
var bytesRead = fs.Read(buffer, 0, 1024);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));
}
Console.ReadLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment