The ninth set of samples discusses migrating existing asynchronous programming models to the upcoming async syntax. The first sample shows how you can wrap code that uses the existing Asynchronous Programming Model library to use the new async features.
public async void AsyncFromAPM()
{
var response = await WebRequest.Create("http://www.weather.gov").
GetResponseAsync();
var stream = response.GetResponseStream();
var buffer = newbyte[1024];
int count;
while ((count = await ReadAsync(stream, buffer, 0, 1024)) > 0)
{
Console.Write(Encoding.UTF8.GetString(buffer, 0, count));
}
}
publicstatic Task<int> ReadAsync(Stream stream, byte[] buffer,
int offset, int count)
{
var tcs = new TaskCompletionSource<int>();
stream.BeginRead(buffer, offset, count, iar =>
{
try { tcs.TrySetResult(stream.EndRead(iar)); }
catch (Exception exc) { tcs.TrySetException(exc); }
}, null);
return tcs.Task;
}
private CancellationTokenSource cts;
public async Task AsyncFromEAP()
{
cts = new CancellationTokenSource();
var progress = new EventProgress<DownloadProgressChangedEventArgs>();
progress.ProgressChanged += (sender, e) =>
{ ProgressBar.Value = e.Value.ProgressPercentage; };
try
{
WriteLinePageTitle(await DownloadStringAsync(new Uri("http://www.weather.gov"),
cts.Token, progress));
}
catch
{
Console.WriteLine("Downloading canceled.");
}
}
publicstatic Task<string> DownloadStringAsync(Uri address,
CancellationToken cancel, IProgress<DownloadProgressChangedEventArgs> progress)
{
// Create the task to be returned
var tcs = new TaskCompletionSource<string>(address);
var webClient = new WebClient();
// Register the cancellation token
var ctr = cancel.Register(webClient.CancelAsync);
// Setup the callback event handlers
webClient.DownloadProgressChanged += (s, e) => progress.Report(e);
webClient.DownloadStringCompleted += (s, e) =>
{
ctr.Dispose();
if (e.Error != null) tcs.TrySetException(e.Error);
elseif (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
// Start the async operation.
webClient.DownloadStringAsync(address, tcs);
// Return the task that represents the async operation
return tcs.Task;
}
ublic staticvoid CopyTo(Stream source, Stream destination)
{
// Old synchronous implementation:
var buffer = newbyte[0x1000];
int bytesRead;
long totalRead = 0;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, bytesRead);
totalRead += bytesRead;
}
}
publicstatic async Task CopyToAsync(Stream source, Stream destination,
CancellationToken cancellationToken,
IProgress<long> progress)
{
// New asynchronous implementation:
var buffer = newbyte[0x1000];
int bytesRead;
long totalRead = 0;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await destination.WriteAsync(buffer, 0, bytesRead);
cancellationToken.ThrowIfCancellationRequested(); // cancellation support
totalRead += bytesRead;
progress.Report(totalRead); // progress support
}
}
I create content for .NET Core. My work appears in the .NET Core documentation site. I'm primarily responsible for the section that will help you learn C#.
All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.