Created
May 9, 2014 04:35
-
-
Save dschenkelman/e0f78a13a9298120efd0 to your computer and use it in GitHub Desktop.
Asynchronous I/O in C#: Introduction
This file contains hidden or 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
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; } | |
} |
This file contains hidden or 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
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(); | |
} |
This file contains hidden or 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
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