Created
October 8, 2012 16:56
-
-
Save clemensv/3853572 to your computer and use it in GitHub Desktop.
Writes
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
namespace Writing | |
{ | |
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Threading; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
for (int i = 0; i < 3; i++) | |
{ | |
AsyncWrites(); | |
AsyncWritesQueued(); | |
SyncWrites(); | |
} | |
} | |
static void AsyncWrites() | |
{ | |
Action write = null; | |
var sw = new Stopwatch(); | |
sw.Start(); | |
var mre = new ManualResetEvent(false); | |
long bytesWritten = 0; | |
long bytesToWrite = 100*1024*1024; | |
var data = new byte[16*1024*1024]; | |
var fs = new FileStream("foo", FileMode.Create, FileAccess.Write, FileShare.None, data.Length, | |
FileOptions.Asynchronous | FileOptions.WriteThrough); | |
write = () => fs.BeginWrite(data, 0, data.Length, | |
ar => | |
{ | |
fs.EndWrite(ar); | |
bytesWritten += data.Length; | |
if (bytesWritten < bytesToWrite) | |
{ | |
write(); | |
} | |
else | |
{ | |
fs.Flush(); | |
fs.Close(); | |
sw.Stop(); | |
mre.Set(); | |
} | |
}, null); | |
write(); | |
mre.WaitOne(); | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
} | |
static void AsyncWritesQueued() | |
{ | |
Action write = null; | |
var sw = new Stopwatch(); | |
sw.Start(); | |
var mre = new ManualResetEvent(false); | |
long bytesWritten = 0; | |
long bytesToWrite = 100*1024*1024; | |
var data = new byte[16*1024*1024]; | |
var fs = new FileStream("foo3", FileMode.Create, FileAccess.Write, FileShare.None, data.Length, | |
FileOptions.Asynchronous | FileOptions.WriteThrough); | |
write = () => fs.BeginWrite(data, 0, data.Length, | |
ar => | |
{ | |
fs.EndWrite(ar); | |
bytesWritten += data.Length; | |
if (bytesWritten >= bytesToWrite) | |
{ | |
fs.Flush(); | |
fs.Close(); | |
sw.Stop(); | |
mre.Set(); | |
} | |
}, null); | |
for (int i = 0; i < bytesToWrite; i += data.Length) | |
{ | |
write(); | |
} | |
mre.WaitOne(); | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
} | |
static void SyncWrites() | |
{ | |
var sw = new Stopwatch(); | |
sw.Start(); | |
long bytesWritten = 0; | |
long bytesToWrite = 100*1024*1024; | |
var data = new byte[16*1024*1024]; | |
var fs = new FileStream("foo2", FileMode.Create, FileAccess.Write, FileShare.None, data.Length, | |
FileOptions.WriteThrough); | |
do | |
{ | |
fs.Write(data, 0, data.Length); | |
bytesWritten += data.Length; | |
} while (bytesWritten < bytesToWrite); | |
fs.Flush(); | |
fs.Close(); | |
sw.Stop(); | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment