The next async samples explore how to report progress while async operations execute.
There’s only one sample here, but it’s somewhat more involved. The client method (calling async methods) method follows:
public async Task AsyncProgressPolling()
{
cts = new CancellationTokenSource();
var progress = new EventProgress<GetAllPingsPartialResult>();
try
{
progress.ProgressChanged += (source, e) =>
{
ProgressBar.Value = e.Value.Count % 100;
};
foreach (var item in await GetAllPingsAsync(cts.Token, progress))
{
Console.WriteLine(item);
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation canceled.");
}
}
public async Task<string[]> GetAllPingsAsync(
CancellationToken cancel, IProgress<GetAllPingsPartialResult> progress)
{
var sites = new List<string>();
for (int i = 0; i < 30; i++)
{
sites.Add("http://www.microsoft.com");
sites.Add("http://msdn.microsoft.com");
sites.Add("http://www.xbox.com");
}
var results = new List<string>(sites.Count);
foreach (var site in sites)
{
cancel.ThrowIfCancellationRequested();
var time = DateTime.UtcNow;
try {await new WebClient().DownloadStringTaskAsync(site);}
catch {}
var ms = (DateTime.UtcNow - time).TotalMilliseconds;
results.Add(String.Format("[{0}] {1}", ms, site));
if (progress != null)
progress.Report(new GetAllPingsPartialResult()
{
Pings = new ReadOnlyCollection<string>(results),
Count = results.Count
});
}
return results.ToArray();
}
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.