- C# Asynchronous Programming
- C# Asynchronous Program 1
- C# Asynchronous Program 2
- C# Asynchronous Program 3
In this example we have three blocking operations in a Windows Presentation Foundation (WPF) program. We want to download HTML from 3 different websites. We want to first display a message box telling the user to wait. This will be displayed immediately. After the user clicks OK in this message box they will wait for a second or two before seeing the other three message boxes. Meanwhile, the program main window is responsive. It is not frozen. You can move it around or re-size the main window. This give the user a better UX (user experience).
I also took the opportunity to show the message box with a title, an icon and specifically specifying the OK button.
using System.Threading.Tasks;
using System.Windows;
using System.Net;
namespace Ayschronous3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var getHtmlTask1 = GetHtmlAsync("https://begincodingnow.com");
var getHtmlTask2 = GetHtmlAsync("http://msdn.microsoft.com");
var getHtmlTask3 = GetHtmlAsync("https://www.w3schools.com");
MessageBox.Show("Waiting for the 3 tasks to complete..."); // executes immediately
var html1 = await getHtmlTask1;
var html2 = await getHtmlTask2;
var html3 = await getHtmlTask3;
// the following 3 message boxes execute AFTER html is downloaded.
MessageBox.Show(html1.Substring(0, 500),"begincodingnow.com", MessageBoxButton.OK, MessageBoxImage.Information);
MessageBox.Show(html2.Substring(0, 500),"msdn.microsoft.com", MessageBoxButton.OK, MessageBoxImage.Information);
MessageBox.Show(html3.Substring(0, 500),"www.w3schools.com", MessageBoxButton.OK, MessageBoxImage.Information);
}
public async Task<string> GetHtmlAsync(string url)
{
var webClient = new WebClient();
return await webClient.DownloadStringTaskAsync(url);
}
}
}