Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Created September 11, 2018 05:03
Show Gist options
  • Save fearofcode/5db4af36f4166860aa88b552bf626fa6 to your computer and use it in GitHub Desktop.
Save fearofcode/5db4af36f4166860aa88b552bf626fa6 to your computer and use it in GitHub Desktop.
Simple async/await example in WPF
<Window x:Class="asyncawait.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:asyncawait"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="450">
<DockPanel>
<Button Name="buttonAsync"
Content="Async Example"
DockPanel.Dock="Top"
Click="buttonAsync_Click" />
<Button Name="buttonResponds"
Content="UI still responds during background task"
DockPanel.Dock="Top"
Click="buttonResponds_Click" />
<TextBox Name="textBoxResults"
DockPanel.Dock="Bottom"
Margin="0,20,0,0"
TextWrapping="Wrap"
FontFamily="Consolas"
AcceptsReturn="True" />
</DockPanel>
</Window>
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace asyncawait
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void buttonAsync_Click(object sender, RoutedEventArgs e)
{
buttonAsync.IsEnabled = false;
var slowTask = Task.Run(() => SlowTask());
textBoxResults.AppendText("Processing. The UI should continue to respond.\n");
await slowTask;
textBoxResults.AppendText(slowTask.Result.ToString());
buttonAsync.IsEnabled = true;
}
private string SlowTask()
{
Thread.Sleep(5000);
return "Work complete! Zug zug.\n";
}
private void buttonResponds_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("UI still works");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment