C# Asynchronous Program 1


This entry is part 2 of 4 in the series C# Asynchronous

We are now going to demonstrate C# asynchronous programming with a Windows Presentation Foundation (WPF) program. We have a post that shows the steps for setting up a WPF program in Visual Studio 2017 that is called C# WPF Hello World 2.

After you have simply created your project and added a button by dragging it from the Toolbox, double-click the button to gain access to the code window. Add two using statements: using System.IO; and using System.Net;.

Below is the code listing for the Button_Click event, showing all of the code we added. In this example we are going out to begincodingnow.com and downloading and saving the Html to a file. This will take a few seconds to complete and we don’t want the user to experience a frozen screen while it downloads. Operations that take time are called blocking operations.

When we click the button we are executing blocking operation that will take a bit of time, only a few seconds, however. The button calls the method/function we wrote called DownloadHtmlAsync. We inserted the keywords async, await and Task in the appropriate places. All asynchronous methods need to be decorated with the async keyword. The Task is the object that encapsulates the state of an asynchronous operation. There is Task and Task<>, where the second one is the generic one that you use if you are returning something. If the method is void, you use the non-generic form Task. Since .NET 4.5, most blocking operations have a synchronous and an asynchronous version. Don’t just pick the one with Asyc as a suffix because that one will be the legacy one. Use your Intellisense to see what is awailable. Use the one that has TaskAsync as a suffix.

We can only use the await operator in an async method. We need to add the async keyword to our method definition. Programmers do not have to partition our code with a callback method because await tells the compiler to do it for us.

using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;

namespace AysnchronousProgramming
{
    /// <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");
        }
        public async Task DownloadHtmlAsync(string url)
        {
            var webClient = new WebClient();
            var html = await webClient.DownloadStringTaskAsync(url);
            
            // the code below would be the "callback" code
            using (var streamWriter = new StreamWriter(@"d:\temp\result.html"))
            {
                await streamWriter.WriteAsync(html);
            }
            MessageBox.Show("done");
        }
        public void DownloadHtml(string url)
        {   // not asynchronous - just shown here for comparison
            var webClient = new WebClient();
            var html = webClient.DownloadString(url);

            using (var streamWriter = new StreamWriter(@"d:\temp\result_test.html"))
            {
                streamWriter.Write(html);
            }
        }
    }
}

In ASP.NET programs the UI is not on the server but it is running on the browser on the client’s machine. Does this new asynch model improve web applications? Yes it does. How? When a request comes to the Web server. a thread is allocated to that request. If inside that thread there is a blocking operation, that thread is going to be busy. Each computer has a limited number of threads available for use. If there are a lost of concurrent connections on the server and all of our threads are busy. Using asynchronous programming we can return control to the thread when we encounter a blocking operation so that the thread can handle another request. It is as though the thread can pass the blocking operation off somewhere else so that it can free itself up to handle the next request and the next one.

Series Navigation<< C# Asynchronous ProgrammingC# Asynchronous Program 2 >>