【问题标题】:documentviewer and backgroundworker文档查看器和后台工作人员
【发布时间】:2016-08-25 23:34:13
【问题描述】:

加载和查看我的 xps 文档工作正常,但加载文档需要很长时间,而且您知道这会导致 UI 看起来不活动。

XpsDocument xpsDocument = new XpsDocument(@"Resources\maintManual.xps", FileAccess.Read);  
documentViewer1.Document = xpsDocument.GetFixedDocumentSequence();

所以,我正在尝试通过后台工作人员加载文档:

private void maintBtn_TouchDown(object sender, TouchEventArgs e) // load and view maint manual
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.DoWork += worker_DoWork;
    worker.ProgressChanged += worker_ProgressChanged;
    worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    worker.RunWorkerAsync();
}

void worker_DoWork(object sender, DoWorkEventArgs e) // do work
{
    XpsDocument xpsDocument = new XpsDocument(@"Resources\maintManual.xps", FileAccess.Read);  
    documentViewer1.Document = xpsDocument.GetFixedDocumentSequence();   
}

一旦执行“Dowork”,用户界面就会“崩溃”(完全锁定)。我似乎找不到原因。有没有更好的方法通过后台工作人员调用文档?就像我说的那样,Dowork 括号中的代码在后台工作人员之外就可以正常工作,所以我知道代码是正确的。一旦使用了后台工作程序,它就会停止工作。如果我没有提供足够的信息,请提前原谅我。我是初级程序员,也是这个网站的新手。

【问题讨论】:

标签: c# wpf backgroundworker documentviewer


【解决方案1】:

只能从 UI 线程更改 UI。 例如,除非从 main/ui 线程,否则您无法访问用户控件的某些属性。

我会推荐: 您的 IO 方法在新任务中运行,但此任务的结果适用于主线程中的 UI 控件。

我不知道XpsDocument 是什么,但我想这应该可以:

  private async void maintBtn_TouchDown(object sender, TouchEventArgs e) // load and view maint manual
    {
        XpsDocument xpsDocument = await Task.Run(() => new XpsDocument(@"Resources\maintManual.xps", FileAccess.Read));
        documentViewer1.Document = xpsDocument.GetFixedDocumentSequence();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多