前回のエントリで触れた、.NETのプロパティから非同期メソッドを呼び出してしまうと同期コンテキストにより意図しないデッドロックが発生することがある…という例を簡単なサンプルで紹介します。
本例はWFPの場合ですが、同期コンテキスト(SynchronizationContext)を利用しているフレームワーク(WinForms/Blazor等)でも同様の問題が生じます。
同期コンテキストで処理したいだけのためMVVMなどは意識していません。
問題
今回の問題を再現するサンプルソースです。問題の再現に必要な部分のみで簡略化しています。
MainWindow.xaml:
<Window x:Class="async_deadlock_20240922.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:async_deadlock_20240922"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Button Content="非同期処理実行"
Click="ButtonClicked"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Grid>
</Window>
MainWindow.cs:
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace async_deadlock_20240922;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonClicked(object sender, RoutedEventArgs e)
{
var model = new SomeModelClass();
// プロパティを表示
MessageBox.Show(this, model.SomeProp);
}
// モデルクラス
private class SomeModelClass
{
// プロパティ
public string SomeProp
{
get
{
// 非同期処理結果を同期で待機
return SomeFuncAsync().Result;
}
}
// 非同期処理
private async Task<string> SomeFuncAsync()
{
// 既にResultでUIスレッドがブロックされているため
// awaitでUIスレッドに戻れずデッドロックが発生する
await Task.Delay(5000);
// 同期コンテキストをキャプチャしなければデッドロック
// は発生しないがawait後の処理がスレッドプール上の
// スレッドで実行されることに注意が必要
//await Task.Delay(5000).ConfigureAwait(false);
return "SomeResult";
}
}
}
説明
起動すると画面中央に非同期処理実行
ボタンが表示されます。
当該ボタンを押下すると非同期処理の完了を同期的に待機しますが、非同期処理内のawaitがロック状態となっているUIスレッドに戻れなくなりデッドロックが発生します。
デッドロック発生時のシーケンス:
上記例の場合は非同期処理内のawaitに対してConfigureAwait(false)
で同期コンテキストをキャプチャしないこによりデッドロックを回避可能ですが、デッドロックになる根本的な原因は非同期処理を同期処理であるプロパティで扱おうとしていることのため、基本的には以下のように非同期で処理する必要があります。
MainWindow.cs:
using System;
using System.Threading.Tasks;
using System.Windows;
namespace async_deadlock_20240922
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void ButtonClicked(object sender, RoutedEventArgs e)
{
var model = new SomeModelClass();
// プロパティを非同期で取得して表示
string result = await model.GetSomePropAsync();
MessageBox.Show(this, result);
}
}
// モデルクラス
private class SomeModelClass
{
// 非同期メソッドとしてプロパティ値を取得
public async Task<string> GetSomePropAsync()
{
return await SomeFuncAsync();
}
// 非同期処理
private async Task<string> SomeFuncAsync()
{
await Task.Delay(5000);
return "SomeResult";
}
}
}
以上です。