[英]Reporting Progress from COM/STA Thread to WPF UI thread
我在使用COM和Acrobat SDK打印PDF的应用程序上工作。 该应用程序是用C#,WPF编写的,我试图弄清楚如何在单独的线程上正确运行打印。 我已经看到BackgroundWorker使用线程池,因此无法将其设置为STA。 我确实知道如何创建STA线程,但是不确定如何报告STA线程的进度:
Thread thread = new Thread(PrintMethod);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join(); //Wait for the thread to end
如何在这样创建的STA线程中向WPF ViewModel报告进度?
其实不是,你需要从 而是一个(现有)STA线程,其中UI运行不报告进度。
您可以通过BackgroundWorker
函数(在启动BackgroundWorker
的线程上传递ReportProgress
-这应该是您的UI线程)或使用UI线程的Dispatcher
(通常使用Dispatcher.BeginInvoke
)来实现。
编辑:
对于您的情况,使用BackgroundWorker
的解决方案将不起作用,因为其线程不是STA。 因此,您只需要使用通常的DispatcherlInvoke
:
// in UI thread:
Thread thread = new Thread(PrintMethod);
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
void PrintMethod() // runs in print thread
{
// do something
ReportProgress(0.5);
// do something more
ReportProgress(1.0);
}
void ReportProgress(double p) // runs in print thread
{
var d = this.Dispatcher;
d.BeginInvoke((Action)(() =>
{
SetProgressValue(p);
}));
}
void SetProgressValue(double p) // runs in UI thread
{
label.Content = string.Format("{0}% ready", p * 100.0);
}
如果当前对象没有Dispatcher
,则可以从UI对象或视图模型中获取它(如果使用的话)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.