//Wait Async use:
private async void button1_Click(object sender, EventArgs e)
{
// Call the method that runs asynchronously.
string result = await WaitAsynchronouslyAsync();
// Call the method that runs synchronously.
//string result = await WaitSynchronously ();
// Display the result.
textBox1.Text += result;
}
// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
await Task.Delay(10000);
return “Finished”;
}
// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
// Add a using directive for System.Threading.
Thread.Sleep(10000);
return “Finished”;
}
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1)
GetPageSizeAsync(args[1]).Wait();
else
Console.WriteLine(“Enter at least one URL on the command line.”);
}
private static async Task GetPageSizeAsync(string url)
{
var client = new HttpClient();
var uri = new Uri(Uri.EscapeUriString(url));
byte[] urlContents = await client.GetByteArrayAsync(uri);
Console.WriteLine($”{url}: {urlContents.Length/2:N0} characters”);
}
}
// The following call from the command line:
// await1 http://docs.microsoft.com
// displays output like the following:
// http://docs.microsoft.com: 7,967 characters
//In a separate class:
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
class Example
{
static async Task Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length < 2)
throw new ArgumentNullException(“No URIs specified on the command line.”);
// Don’t pass the executable file name
var uris = args.Skip(1).ToArray();
long characters = await GetPageLengthsAsync(uris);
Console.WriteLine($”{uris.Length} pages, {characters:N0} characters”);
}
private static async Task<long> GetPageLengthsAsync(string[] uris)
{
var client = new HttpClient();
long pageLengths = 0;
foreach (var uri in uris)
{
var escapedUri = new Uri(Uri.EscapeUriString(uri));
string pageContents = await client.GetStringAsync(escapedUri);
Interlocked.Add(ref pageLengths, pageContents.Length);
}
return pageLengths;
}
}