0

我正在开发一个使用 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 报告进度?

4

1 回答 1

3

实际上不是,您需要报告进度,而不是来自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 对象或视图模型(如果您使用一个)中获取它。

于 2012-11-05T21:51:53.677 回答