我有一个带有GUI组件的COM对象,我们称之为“FileViewer”。此FileViewer组件可以使用方法加载文件,我们称之为“LoadFile”,需要使用UI线程才能工作。要使用LoadFile,必须已添加FileViewer并将其加载到GUI中。 问题是您使用LoadFile加载的文件可能非常大,导致应用程序UI冻结多秒,从而导致糟糕的用户体验。
我的问题是:无论如何都要调用此LoadFile异步而不锁定UI线程,即使它需要加载UI线程。
我尝试了什么:
//My standard approach of doing things async
public async btnPressed (){
await new TaskFactory().StartNew(() => {
myFileViewer.LoadFile("C:\..."); //This still freezes the UI thread
});
}
//Maybe could prevent locking if it's not visible
myFileViewer.Parent = null;
myFileViewer.Visible = false;
myFileViewer.LoadFile("C:\..."); //This still freezes the UI
myFileViewer.Parent = this;
myFileViewer.Visible = true;
//Maybe could create the viewer in a new window "TestProxy" with a new "UI thread", load the file and then insert the viewer back into my first window
Thread thread = new Thread(() => {
new TestProxy().Show();
TestProxy.CreateViewerAndLoadFile("C:\..."); //Does actually not freeze my application
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
//this version actually worked, but the problem is that there seem to be no way to move the viewer back into my original window after loading it into this new one
我非常确定Viewer类本身对LoadFile异步没有任何支持,所以我对这个问题的一般解决方案更感兴趣。只是不觉得它应该是不可能的事情。
PS: GUI组件的名称是“AxInventorViewControl”,我创建了一个实例,“LoadFile”实际上是一行代码axInventorViewControl1.FileName = filePath;