This project has moved. For the latest updates, please go here.

Exeption when using a BackgroundWorker to do the work on a background thread

Aug 6, 2011 at 3:54 AM
Edited Aug 9, 2011 at 3:06 AM

Hi all,

Iam trying to create a progressbar to process open large file but it has exception to thown:

"Exception has been thrown by the target of an invocation.

 ....

at eLecture.Presentation.Views.PageView.System.Waf.Applications.IView.set_DataContext(Object )

at System.Waf.Applications.ViewModel.<>c__DisplayClass2.<.ctor>b__0() in F:\Projects\iUedu\Softwares\GADT\04 Coding\v1.0\ApplicationFramework\WpfApplicationFramework\Applications\ViewModel.cs:line 47

....

"

Screen

Press F5(Debug again) that get other excetion message:

System.InvalidOperationException was unhandled
  Message="The calling thread cannot access this object because a different thread owns it."

Screen 2

My source code in ViewModel:

 public class DialogProgressbarViewModel : ViewModel<IDialogProgressbar>
    {

          private readonly BackgroundWorker m_worker;

        public DialogProgressbarViewModel(IDialogProgressbar view, string zipFile, string extractTo)
            : base(view)
        {           
            m_worker = new BackgroundWorker();
            m_worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            m_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {          

     // do time-consuming work here, calling extract file ...

        }
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           //
        }

     //Properties to binding UI progressbar.

       public int Max
        {
            get;set;
        }

        public long CurrentValue
        {
            get;set;
        }

     }

Help me how to fix this problem?

Thanks,

Coordinator
Aug 18, 2011 at 8:18 PM

Hi,

It seems that you create ViewModel objects in the DoWork method. The DoWork method runs in the background thread but creating ViewModel objects must be done in the main (Dispatcher) thread.

You could move the ViewModel creation code (e.g. container.GetExportedValue<…>) into the RunWorkerCompleted method. This way it should work.

jbe