Last active
August 25, 2019 13:52
-
-
Save kekyo/d57311f4321ad8261f7040c094103fa3 to your computer and use it in GitHub Desktop.
Async operation in WPF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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