Last active
January 11, 2016 20:01
-
-
Save Porges/b68df1da49d80dede51c to your computer and use it in GitHub Desktop.
possible framework bug?
This file contains 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
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Security.AccessControl; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace AtomicAppend | |
{ | |
public static class Program | |
{ | |
public static void Main() | |
{ | |
const string FileName = "atomic.txt"; | |
File.Delete(FileName); | |
/* | |
F5 - should eventually raise this: | |
System.UnauthorizedAccessException: Access to the path is denied. | |
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) | |
at System.IO.FileStream.SetLengthCore(Int64 value) | |
at System.IO.FileStream.BeginWriteCore(Byte[] bytes, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stateObject) | |
at System.IO.FileStream.BeginWriteAsync(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stateObject) | |
at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) | |
at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) | |
at AtomicAppend.Program.<>c.<<Main>b__0_0>d.MoveNext() | |
This only happens with FileOptions.Asynchronous, so there appears to be some interaction | |
between being opened in overlapped mode and failing to use SetEndOfFile (does it need to be used in this case?) | |
*/ | |
const int BufferSize = 1024; | |
const int Tasks = 1000; | |
const int LinesPerTask = 1000; | |
var timer = Stopwatch.StartNew(); | |
Task.WaitAll( | |
Enumerable.Range(0, Tasks).Select( | |
async n => | |
{ | |
using (var fs = | |
new FileStream( | |
FileName, | |
FileMode.Append, | |
FileSystemRights.AppendData, | |
FileShare.Write, | |
BufferSize, | |
FileOptions.Asynchronous)) | |
{ | |
var written = 0; | |
var buffer = new byte[BufferSize]; | |
var s = Encoding.UTF8.GetBytes("I am task: " + n + "\n"); | |
for (int i = 0; i < LinesPerTask; ++i) | |
{ | |
if (written + s.Length > BufferSize) | |
{ | |
try | |
{ | |
await fs.WriteAsync(buffer, 0, written); | |
} | |
catch (UnauthorizedAccessException) | |
{ | |
Debugger.Break(); | |
throw; | |
} | |
written = 0; | |
} | |
Array.Copy(s, 0, buffer, written, s.Length); | |
written += s.Length; | |
} | |
if (written != 0) | |
{ | |
await fs.WriteAsync(buffer, 0, written); | |
} | |
} | |
}).ToArray()); | |
Console.WriteLine("Elapsed: " + timer.Elapsed); | |
Console.WriteLine("Lines: {0} (should be: {1})", File.ReadLines(FileName).Count(), Tasks * LinesPerTask); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment