Skip to content

Instantly share code, notes, and snippets.

@kekyo
Last active August 25, 2019 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kekyo/d57311f4321ad8261f7040c094103fa3 to your computer and use it in GitHub Desktop.
Save kekyo/d57311f4321ad8261f7040c094103fa3 to your computer and use it in GitHub Desktop.
Async operation in WPF
<Window x:Class="WpfApp1.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<DockPanel>
<Button DockPanel.Dock="Bottom" Click="Button_Click" Content="Append" />
<TextBlock x:Name="input" />
</DockPanel>
</Window>
using Nito.AsyncEx;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
private readonly Timer timer;
private readonly AsyncLock locker = new AsyncLock();
public MainWindow()
{
InitializeComponent();
this.timer = new Timer(timerCallback);
this.Loaded += (s, e) => this.timer.Change(1000, 1000);
}
private async Task WriteTextAsync(string text)
{
using (await locker.LockAsync())
{
using (var fs = new FileStream("output.txt", FileMode.Append, FileAccess.Write, FileShare.None, 65536, true))
{
var tw = new StreamWriter(fs, Encoding.UTF8);
await tw.WriteLineAsync(text);
await tw.FlushAsync();
}
}
}
private void timerCallback(object state)
{
var task = this.WriteTextAsync("Timer periodic.");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var task = this.WriteTextAsync(this.input.Text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment