1

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.

  • Look at this: http://stackoverflow.com/questions/1862590/how-to-update-gui-with-backgroundworker maybe help. – BWA Aug 25 '16 at 15:03

1 Answers1

0

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();
    }
Mr.B
  • 3,484
  • 2
  • 26
  • 40