Skip to content

Instantly share code, notes, and snippets.

@kekyo
Created August 25, 2019 14:14
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/1d6c351d0518211366927a6aee0829ad to your computer and use it in GitHub Desktop.
Save kekyo/1d6c351d0518211366927a6aee0829ad to your computer and use it in GitHub Desktop.
Causes reentrant by invalid monitor lock usage with async/await method.
<Window x:Class="WpfApp2.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 System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
// DANGEROUS DIRTY HACK: It's going to ignore multiple locking at single main thread. (It's nonsense and cause reentrants)
// lock (this)
Monitor.Enter(this);
try
{
Trace.WriteLine($"Begin: Thread={Thread.CurrentThread.ManagedThreadId}");
using (var fs = new FileStream("output.txt", FileMode.Append, FileAccess.Write, FileShare.None, 65536, true))
{
var tw = new StreamWriter(fs, Encoding.UTF8);
// Maybe causes reentrant below awaiters by owned main thread.
await tw.WriteLineAsync("Clicked.");
await Task.Delay(1000); // Simulate long awaited code.
await tw.FlushAsync();
}
Trace.WriteLine($"End: Thread={Thread.CurrentThread.ManagedThreadId}");
}
finally
{
Monitor.Exit(this);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment