【问题标题】:Reporting Progress from COM/STA Thread to WPF UI thread从 COM/STA 线程向 WPF UI 线程报告进度
【发布时间】:2012-11-05 21:48:30
【问题描述】:

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

【问题讨论】:

    标签: c# wpf com sta acrobat-sdk


    【解决方案1】:

    实际上不是,您需要报告的进度不是来自,而是运行 UI 的(已经存在的)STA 线程。

    您可以通过 BackgroundWorker 函数(ReportProgress 在启动 BackgroundWorker 的线程上传递 - 这应该是您的 UI 线程)或使用 UI 线程的 Dispatcher(通常使用 @ 987654327@).


    编辑:
    对于您的情况,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 对象或视图模型(如果您使用的话)中获取它。

    【讨论】:

    • 但是COM组件也需要在STA线程中运行,我不希望它在UI线程中运行,因为它需要很长时间。
    • @jle:是的,COM 可以在自己的 STA 线程中运行。无论如何,UI 线程也是一个 STA。如果你不能使用BackgroundWorker(因为它的工作线程不是STA),你可以只用Dispatcher.BeginInvoke报告进度。
    • 所以有这个:dotnetventures.wordpress.com/2011/07/30/…,它显示了如何做到这一点,但我不明白为什么我可以使用调度程序创建一个线程?
    • 这是一场胜利——现在说得通了。
    • @jle:确实,不需要像您提到的文章中那样的额外线程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2012-09-09
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多