Skip to content

Instantly share code, notes, and snippets.

@gogsbread
Created January 2, 2013 23:34
Show Gist options
  • Save gogsbread/4439386 to your computer and use it in GitHub Desktop.
Save gogsbread/4439386 to your computer and use it in GitHub Desktop.
Basic Asynchronous writer example.
using System;
using System.IO;
using System.Threading;
namespace dotNetPlayGround
{
class AsyncState
{
public string name;
public Stream stream = null;
}
class AsyncWriter
{
static void Main()
{
Stream sr = new FileStream("source.txt", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[sr.Length];
int bytesRead = sr.Read(buffer, 0, buffer.Length);
Stream sw = new FileStream("temp.txt", FileMode.OpenOrCreate, FileAccess.Write);
AsyncState state = new AsyncState();
state.name = "tempt.txt";
state.stream = sw;
IAsyncResult writeResult = sw.BeginWrite(buffer, 0, buffer.Length,
(result) => {
AsyncState s = (AsyncState)result.AsyncState;
s.stream.EndWrite(result);
Console.WriteLine("Name:{0},Length:{1}", s.name, s.stream.Length);
Console.Write(state.name == s.name);
Console.Write(object.ReferenceEquals(state, s));
}
, state);
while (!writeResult.IsCompleted) { }
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment