WPF 应用程序具有使用以下方法从单独的文件加载用户控件的操作XamlReader.Load()
:
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
报错:调用线程必须是STA,因为很多UI组件都需要这个
所以,我走了另一条路:
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 响应式地执行此操作?