Spoiler (Click to View)
MSDN Wrote:The Async and Await keywords in Visual Basic and the async and await keywords in C# are the heart of async programming. By using those two keywords, you can use resources in the .NET Framework or the Windows Runtime to create an asynchronous method almost as easily as you create a synchronous method. Asynchronous methods that you define by using async and await are referred to as async methods.
Let's start now. First up create a new WPF project targeting .net 4.5 in visual studio 2012 and name is Asynchronus Programming
Now let's add some controls to MainWindow. I added a button named start and a progress bar named pb. Create event handler for button click this can be done easily by double clicking and set the isIndertiminate property of progress bar to false. The resulting XAML is
Code:
<Window x:Class="Asynchronus_Programming.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="180" Width="223">
<Grid Margin="0,0,2,4">
<Button x:Name="Start" Content="Begin" HorizontalAlignment="Left" Margin="130,105,0,0" VerticalAlignment="Top" Width="75" Height="25" Click="Start_Click"/>
<ProgressBar x:Name="pb" HorizontalAlignment="Left" Height="23" Margin="10,59,0,0" VerticalAlignment="Top" Width="195" IsIndeterminate="False"/>
</Grid>
</Window>
Now let's write some code. First up notice the Sytem.Threading.Tasks namespace , this is the backbone of this tutorial.
Next modify the button click method to have the keyword async, this is necessary
Add a reference to System.Net namespace.
Write an async function called DownloadGoogleAsync with return type of Task<string> . This method returns a string . Add the following code(You can replace url with any website you like but it's just easy to use google)
CSHARP Code
- Task<string> Result = webClient.DownloadStringTaskAsync("http://google.com");
- string result=await Result;
- Dispatcher.Invoke(() => pb.IsIndeterminate = false);
- return result;
Now it should look like
Finally add the following code in the button click event
CSHARP Code
- Task<string> Result = DownloadGoogleAsync();
- pb.IsIndeterminate = true;
- MessageBox.Show(await Result);
Now compile it and see the magic of async programming. Hoping that this helped you also please let me know about any mistakes.