I just took a piece of code from this blog, to show how it makes our lives easier :)
Synchronous example:
public static void CopyTo(Stream source, Stream destination)
{
byte[] buffer = new byte[0x1000];
int numRead;
while((numRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, numRead);
}
}
Asynchronous Programming Model:
public static IAsyncResult BeginCopyTo(Stream source, Stream destination)
{
var tcs = new TaskCompletionSource();
byte[] buffer = new byte[0x1000];
Action readWriteLoop = null;
readWriteLoop = iar =>
{
try
{
for (bool isRead = iar == null; ; isRead = !isRead)
{
switch (isRead)
{
case true:
iar = source.BeginRead(buffer, 0, buffer.Length, readResult =>
{
if (readResult.CompletedSynchronously) return;
readWriteLoop(readResult);
}, null);
if (!iar.CompletedSynchronously) return;
break;
case false:
int numRead = source.EndRead(iar);
if (numRead == 0)
{
tcs.TrySetResult(true);
return;
}
iar = destination.BeginWrite(buffer, 0, numRead, writeResult =>
{
try
{
if (writeResult.CompletedSynchronously) return;
destination.EndWrite(writeResult);
readWriteLoop(null);
}
catch(Exception e) { tcs.TrySetException(e); }
}, null);
if (!iar.CompletedSynchronously) return;
destination.EndWrite(iar);
break;
}
}
}
}
catch(Exception e) { tcs.TrySetException(e); }
};
readWriteLoop(null);
return tcs.Task;
}
public static void EndCopyTo(IAsyncResult asyncResult)
{
((Task)asyncResult).Wait();
}
New C# language async support:
public static async void CopyToAsync(Stream source, Stream destination)
{
byte[] buffer = new byte[0x1000];
int numRead;
while((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destination.WriteAsync(buffer, 0, numRead);
}
}
No comments:
Post a Comment