【テクニカル・上級編】【中級者・実務】VB.NETのWPFアプリにおけるINotifyDataErrorInfoインターフェースによる非同期入力検証 – Visual Basic (VB / VB.NET)解析バイブル

スポンサーリンク
スポンサーリンク

同期の呪縛を解く:WPFにおける `INotifyDataErrorInfo` による非同期バリデーションの極意

エンタープライズ領域のアプリケーション開発において、ユーザー入力の検証(バリデーション)は、単なる「値のチェック」ではない。それは、データの整合性を守る最後の砦であり、不適切なデータがバックエンドのレガシーシステムやDBを汚染することを防ぐための、防波堤である。

長年、我々は `IDataErrorInfo` という、シンプルだが極めて制約の強いインターフェースに頼ってきた。しかし、現代のシステムにおいて、バリデーションはもはやローカルな型チェックに留まらない。外部APIの呼び出し、データベースへの重複チェック、複雑な業務ロジックの計算――これらはすべて「時間」を消費する。

UIスレッドをブロックする同期的なバリデーションは、ユーザー体験(UX)を破壊する。数ミリ秒のフリーズが、プロフェッショナルの作業リズムを狂わせるのだ。

本稿では、WPFにおける真の非同期バリデーションを実現する `INotifyDataErrorInfo` の実装、およびメモリ効率とパフォーマンスを極限まで高めるためのアーキテクチャについて、その真髄を解説する。

1. `IDataErrorInfo` の限界と `INotifyDataErrorInfo` の必然性

まず、なぜ従来の `IDataErrorInfo` では不十分なのかを整理しておく。

特徴 `IDataErrorInfo` `INotifyDataErrorInfo`
検証タイミング プロパティへのアクセス時(同期) イベント駆動(非同期可能)
エラー数 プロパティにつき1件のみ 1つのプロパティに複数件可能
非同期処理 実質不可能(UIスレッドを占有) 標準でサポート
通知メカニズム プロパティ変更通知に依存 `ErrorsChanged` イベントによる明示的通知

`IDataErrorInfo` は、プロパティの `get` アクセサが呼ばれた瞬間に結果を返さなければならない。ここに非同期処理を組み込むことは不可能であり、無理に行おうとすればUIスレッドのデッドロックや、アプリケーションの応答停止(Not Responding)を招く。

一方、`INotifyDataErrorInfo` は、検証結果が準備できたタイミングで `ErrorsChanged` イベントを発生させることができる。この「後出し」ができる設計こそが、非同期バリデーションの鍵となる。

2. 極限のアーキテクチャ:`ValidationBase` の実装

実務において、各 ViewModel にバリデーションロジックを散乱させるのは悪手である。再利用性と保守性を担保するため、基底クラスとして `ValidationBase` を構築する。

ここで重要なのは、「デバウンス(Debounce)」の実装である。ユーザーが文字を入力するたびにAPIを叩くような愚行は、ネットワーク帯域とサーバーリソースを無駄に浪費する。入力が止まってから一定時間後に検証を開始する制御が必要だ。

Imports System.Collections
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Imports System.Threading

''' <summary>
''' 非同期バリデーションを司る基底クラス。
''' メモリリークを防ぎ、非同期処理のキャンセルを適切に管理する。
''' </summary>
Public MustInherit Class ValidationBase
    Implements INotifyPropertyChanged, INotifyDataErrorInfo

    ' エラー情報の格納用。DictionaryのKeyはプロパティ名。
    Private ReadOnly _errors As New Dictionary(Of String, List(Of String))()
    
    ' 非同期検証のキャンセル用トークン
    Private _cts As CancellationTokenSource

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    Public Event ErrorsChanged As EventHandler(Of DataErrorsChangedEventArgs) Implements INotifyDataErrorInfo.ErrorsChanged

    ''' <summary>
    ''' 指定したプロパティにエラーがあるかを確認。
    ''' </summary>
    Public ReadOnly Property HasErrors As Boolean Implements INotifyDataErrorInfo.HasErrors
        Get
            Return _errors.Any(Function(x) x.Value.Any())
        End Get
    End Property

    ''' <summary>
    ''' エラーリストを取得。
    ''' </summary>
    Public Function GetErrors(propertyName As String) As IEnumerable
        Implements INotifyDataErrorInfo.GetErrors
        If String.IsNullOrEmpty(propertyName) Then Return Nothing
        Return If(_errors.ContainsKey(propertyName), _errors(propertyName), Nothing)
    End Function

    ''' <summary>
    ''' プロパティの値を更新し、非同期バリデーションをトリガーする。
    ''' </summary>
    Protected Sub SetProperty(Of TType)(ByRef storage As TType, ByVal value As TType, <CallerMemberName> Optional propertyName As String = Nothing)
        If EqualityComparer(Of TType).Default.Equals(storage, value) Then Return

        storage = value
        OnPropertyChanged(propertyName)

        ' バリデーションの実行(デバウンス処理を含む)
        ValidateAsync(propertyName)
    End Sub

    Protected Sub OnPropertyChanged(propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    ''' <summary>
    ''' 非同期バリデーションの制御ロジック。
    ''' </summary>
    Private Sub ValidateAsync(<CallerMemberName> Optional propertyName As String = Nothing)
        ' 前回の未完了タスクをキャンセルする
        _cts?.Cancel()
        _cts = New CancellationTokenSource()
        Dim token = _cts.Token

        ' デバウンス:300ms待機してから実行
        Task.Delay(300, token).ContinueWith(Sub(t)
            If Not t.IsCanceled Then
                PerformValidationAsync(propertyName, token)
            End If
        End Sub, TaskScheduler.Default)
    End Sub

    ''' <summary>
    ''' 実際の検証ロジック。派生クラスでオーバーライドする。
    ''' </summary>
    Protected MustOverride Async Function PerformValidationAsync(propertyName As String, token As CancellationToken) As Task

    ''' <summary>
    ''' エラー情報を登録し、UIに通知する。
    ''' </summary>
    Protected Sub AddError(propertyName As String, error As String)
        If Not _errors.ContainsKey(propertyName) Then
            _errors(propertyName) = New List(Of String)()
        End If

        If Not _errors(propertyName).Contains(error) Then
            _errors(propertyName).Add(error)
            ' UIスレッドでイベントを発生させる
            RaiseErrorsChanged(propertyName)
        End If
    End Sub

    ''' <summary>
    ''' 指定プロパティのエラーをクリアする。
    ''' </summary>
    Protected Sub ClearErrors(propertyName As String)
        If _errors.ContainsKey(propertyName) Then
            _errors(propertyName).Clear()
            RaiseErrorsChanged(propertyName)
        End If
    End Sub

    Private Sub RaiseErrorsChanged(propertyName As String)
        ' WPFのBindingシステムはUIスレッドでの通知を期待する
        App.Current.Dispatcher.Invoke(Sub()
            RaiseEvent ErrorsChanged(Me, New DataErrorsChangedEventArgs(propertyName))
        End Sub)
    End Sub
End Class

3. 実践:業務ロジックへの組み込み

次に、この `ValidationBase` を継承した具体的な ViewModel を見ていく。ここでは、ユーザーIDがデータベースに既に存在するかを非同期でチェックする、という実務で頻出するシナリオを想定する。

''' <summary>
''' ユーザー登録用ViewModelの実装例。
''' </summary>
Public Class UserRegistrationViewModel
    Inherits ValidationBase

    Private _userId As String
    Public Property UserId As String
        Get
            Return _userId
        End Get
        Set(value As String)
            SetProperty(_userId, value)
        End Set
    End Property

    ''' <summary>
    ''' 非同期バリデーションの実装。
    ''' </summary>
    Protected Overrides Async Function PerformValidationAsync(propertyName As String, token As CancellationToken) As Task
        If propertyName = NameOf(UserId) Then
            ' 1. まずは基本バリデーション(同期的なチェックも混ぜる)
            ClearErrors(propertyName)

            If String.IsNullOrWhiteSpace(UserId) Then
                AddError(propertyName, "ユーザーIDは必須です。")
                Return
            End If

            If UserId.Length < 5 Then
                AddError(propertyName, "ユーザーIDは5文字以上必要です。")
                Return
            End If

            ' 2. 重い処理(DB照会やAPI呼び出しを模倣)
            Try
                ' キャンセル・トークンを渡すことで、入力が続いた場合に無駄な通信を防ぐ
                Dim isDuplicate = Await CheckDuplicateUserInDbAsync(UserId, token)
                
                If isDuplicate Then
                    AddError(propertyName, "このユーザーIDは既に登録されています。")
                End If
            Catch ex As OperationCanceledException
                ' キャンセル時は何もしない
            Catch ex As Exception
                ' システムエラーのハンドリング(レガシー連携時の例外など)
                AddError(propertyName, "検証中にシステムエラーが発生しました。")
            End Try
        End If
    End Function

    ''' <summary>
    ''' 擬似的なDB照会メソッド。
    ''' </summary>
    Private Async Function CheckDuplicateUserInDbAsync(id As String, token As CancellationToken) As Task(Of Boolean)
        ' 実際の環境では、ここでDapperやEntity Frameworkを用いたDBアクセスを行う
        Await Task.Delay(1000, token) ' 通信遅延のシミュレーション
        Dim existingUsers = {"admin", "root", "system"}
        Return existingUsers.Contains(id.ToLower())
    End Function
End Class

4. XAML 側での洗練されたフィードバック

UI側では、`Validation.ErrorTemplate` を定義することで、エラー発生時に視覚的に分かりやすいフィードバックを実装する。

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Advanced Validation" Height="200" Width="400">
    
    <Window.Resources>
        <!-- エラー時の赤い枠とツールチップのテンプレート -->
        <ControlTemplate x:Key="ErrorTemplate">
            <StackPanel>
                <AdornedElementPlaceholder x:Name="placeholder"/>
                <TextBlock Text="{Binding [0].ErrorContent}" 
                           Foreground="Red" 
                           FontSize="10" 
                           Margin="0,2,0,0"/>
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>

    <StackPanel Margin="20">
        <Label Content="ユーザーIDを入力してください:"/>
        <TextBox Text="{Binding UserId, UpdateSourceTrigger=PropertyChanged, 
                        ValidationRules={x:Null}, 
                        ValidatesOnNotifyDataErrors=True}"
                 Validation.ErrorTemplate="{StaticResource ErrorTemplate}"
                 Margin="0,5,0,0"/>
        
        <!-- エラー状態の可視化(オプション) -->
        <TextBlock Text="入力内容を確認中..." 
                   Visibility="{Binding HasErrors, Converter={StaticResource BooleanToVisibilityConverter}}" 
                   Foreground="Gray" FontSize="10"/>
    </StackPanel>
</Window>

5. アーキテクトの視点:メモリとパフォーマンスの最適化

この実装において、シニアエンジニアが注視すべきは以下の3点である。

① CancellationToken の徹底

`Task.Delay` や `CheckDuplicateUserInDbAsync` に `CancellationToken` を渡すことは、単なるマナーではない。ユーザーが高速で入力を変更した際、古い `Task` がバックグラウンドで走り続け、無意味な DB 負荷とメモリ消費を引き起こすのを防ぐための、必須の防衛策である。

② Dispatcher の適切な利用

`ErrorsChanged` イベントは、WPF のデータバインディングエンジンが UI を更新するために使用する。これをバックグラウンドスレッドから不用意に発生させると、`InvalidOperationException` が発生するか、あるいは予期せぬタイミングでの UI 更新による競合状態(Race Condition)を招く。必ず `Dispatcher.Invoke` を通して、UI スレッドのコンテキストで通知を行うこと。

③ オブジェクトのライフサイクル

`ValidationBase` を含む ViewModel が破棄される際、`_cts.Cancel()` を呼び出し、進行中のタスクを確実に停止させる必要がある。大規模なアプリケーションでは、ViewModel の生成と破棄が頻繁に行われるため、ここでタスクが「浮遊」すると、メモリリークの温床となる。

結論

`INotifyDataErrorInfo` は、単にエラーを表示するためのインターフェースではない。それは、非同期という現代の計算機環境において、「UI の応答性」と「データの整合性」という、相反する二つの要求を高度に両立させるための設計思想である。

レガシーなシステムをモダンな WPF アプリケーションへと昇華させるには、こうした「見えない部分」の設計にこそ、エンジニアの魂を込めるべきである。

タイトルとURLをコピーしました