实际上不是,您需要报告进度,而不是来自UI运行的(已经存在的)STA 线程。
您可以通过BackgroundWorker
函数(ReportProgress
在启动的线程上传递BackgroundWorker
——这应该是您的 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 对象或视图模型(如果您使用一个)中获取它。