简体   繁体   中英

documentviewer and backgroundworker

Loading and viewing my xps document works just fine but it takes a long time to load the document and as you know it causes the UI to look inactive.

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

So, I am trying to load the document through the backgroundworker:

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();   
}

As soon as the "Dowork" is executed the ui "crashes" (locks up totally). I can't seem to find why. Is there a better way to call the document via the background worker? Like I said, the code in the Dowork brackets works just fine outside of the background worker on it's own, so I know the code is right. Once the background worker is used, it stops working. Please forgive me in advance if I didn't include enough information. I am junior coder and new to this site.

Changes in UI are possible only from UI thread. You cannot access to to some property of user control, for instance, unless from main/ui thread.

What I would recommend: Your IO method run in new Task, but result of this task apply to your UI control in main thread.

I don't know what is XpsDocument , however I suppose this should work:

  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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM