- C# Asynchronous Programming
- C# Asynchronous Program 1
- C# Asynchronous Program 2
- C# Asynchronous Program 3
In this example we will display some of the html we downloaded in a message box in a Windows Presentation Foundation (WPF) program, which is the newest type of Windows program.
We are going to make a few changes to the code. The point of these changes is to show us that we can do some work before waiting for an asynchronous operation. We can immediately display a message box for example that tells the user that they will need to wait for a moment for the operation to complete. We could run any other code at this point that we need to execute immediately. The message box “Waiting…” is not dependent on the result of an asynchronous operation. It’s just a message box.
using System.Net; using System.Threading.Tasks; using System.Windows; namespace AsynchronousProgrammingReturnString { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Button_Click(object sender, RoutedEventArgs e) { //await DownloadHtmlAsync("https://begincodingnow.com"); // if we use await we must use async in method definition. // var html = await GetHtmlAsync("https://begincodingnow.com"); var getHtmlTask = GetHtmlAsync("https://begincodingnow.com"); MessageBox.Show("Waiting for the task to complete..."); // executes immediately var html = await getHtmlTask; MessageBox.Show(html.Substring(0, 500)); // executes after html is downloaded } public async Task<string> GetHtmlAsync(string url) { var webClient = new WebClient(); return await webClient.DownloadStringTaskAsync(url); } } }