Async Await in Windows apps for beginners

4 בMarch 2015

אין תגובות

In basically asynchronous programming may be required a long study, since we running on a single

. UI thread, however we can start with small demo of mining data and live update

.Think about list of items and notification from the server

,Now, if we used regular function the view get freeze until the function return

.But with asynchronous pattern we can continue while the background task is running

:For this demo lets use this xaml

<Window x:Class="AsyncAwaitDemoOnWPF.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <Grid.ColumnDefinitions>

            <ColumnDefinition/>

            <ColumnDefinition/>

            <ColumnDefinition/>

            <ColumnDefinition/>

        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="1">

            <TextBlock>async results</TextBlock>

            <ListBox x:Name="ShowResListBoxAsync"  Height="300" Width="120" />

        </StackPanel>

        <Button Width="100" Height="50" Content="run async ->" Margin="5" Grid.Column="0" Click="Button_Click_2"/>

        <Button Width="100" Height="50" Content="run sync ->" Margin="5" Grid.Column="2" Click="Button_Click"/>

        <StackPanel Grid.Column="3">

            <TextBlock>sync results</TextBlock>

        <ListBox x:Name="ShowResListBoxNonAsync"  Height="300" Width="120" />

        </StackPanel>

    </Grid>

</Window>

:And this codebehind

public partial class MainWindow : Window

  {

      public MainWindow()

      {

          InitializeComponent();

      }


      private  void Button_Click(object sender, RoutedEventArgs e)

      {

          for (int i = 0; i < 100; i++)

          {

              System.Threading.Thread.Sleep(500);

              ShowResListBoxNonAsync.Items.Add(" getting called" + i).ToString();

          }

      }



      private async void Button_Click_2(object sender, RoutedEventArgs e)

      {

          for (int i = 0; i < 100; i++)

          {

              await Task.Delay(500);

              ShowResListBoxAsync.Items.Add(" getting called".ToString());

          }


      }


  }

:And feel the different between the functions

As asynchronous programing the list get updated and actually provide live updates of the changes

.while regular function until finish the work getting freeze

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *