XamlReader.Load()
WPF アプリには、メソッドを使用して別のファイルからユーザー コントロールを読み込む操作があります。
StreamReader mysr = new StreamReader(pathToFile);
DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
ContentControl displayPage = FindName("displayContentControl") as ContentControl;
displayPage.Content = rootObject;
ファイルのサイズが原因でプロセスに時間がかかるため、UI が数秒間フリーズします。
アプリの応答性を維持するために、UI の更新に直接関与しない操作の一部を実行するために、バックグラウンド スレッドを使用しようとしています。
使用しようとするBackgroundWorker
と、エラーが発生しました:多くの UI コンポーネントがこれを必要とするため、呼び出し元のスレッドは STA でなければなりません
だから、私は別の方法に行きました:
private Thread _backgroundThread;
_backgroundThread = new Thread(DoReadFile);
_backgroundThread.SetApartmentState(ApartmentState.STA);
_backgroundThread.Start();
void DoReadFile()
{
StreamReader mysr3 = new StreamReader(path2);
Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action<StreamReader>)FinishedReading,
mysr3);
}
void FinishedReading(StreamReader stream)
{
DependencyObject rootObject = XamlReader.Load(stream.BaseStream) as DependencyObject;
ContentControl displayPage = FindName("displayContentControl") as ContentControl;
displayPage.Content = rootObject;
}
時間のかかる操作はすべて UI スレッドに残っているため、これでは何も解決しません。
このようにしようとすると、すべての解析がバックグラウンドで行われます:
private Thread _backgroundThread;
_backgroundThread = new Thread(DoReadFile);
_backgroundThread.SetApartmentState(ApartmentState.STA);
_backgroundThread.Start();
void DoReadFile()
{
StreamReader mysr3 = new StreamReader(path2);
DependencyObject rootObject3 = XamlReader.Load(mysr3.BaseStream) as DependencyObject;
Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action<DependencyObject>)FinishedReading,
rootObject3);
}
void FinishedReading(DependencyObject rootObject)
{
ContentControl displayPage = FindName("displayContentControl") as ContentControl;
displayPage.Content = rootObject;
}
例外が発生しました:別のスレッドがこのオブジェクトを所有しているため、呼び出し元のスレッドはこのオブジェクトにアクセスできません。(ロードされた UserControl には、エラーを引き起こす可能性のある他のコントロールが存在します)
UI が応答するような方法でこの操作を実行する方法はありますか?