Like many applications, I want to update my status text when the application is doing long computation. I've read articles about Dispatcher and BackgroundWorker. I know I definitely need to make sure the the updates happen in the UI thread. My first try was:
MyView.UpdateStatus( "Please wait" );
LongComputation();
MyView.UpdateStatus( "Ready" );
This does not work because (I think) the LongComputation prevents the status being updated.
So I tried to do this:
BackgroundWorker worker = new BackgroundWorker();
MyView.UpdateStatus( "Please wait");
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
LongComputation();
}
worker.RunWorkerAsync();
MyView.UpdateStatus( "Ready" );
I was hopping that the extra thread will give the UpdateStatus a chance to update status text. It does not work either. One of the reason is that the result of the LongComputation is displayed in a Windows Form. As soon as I put the LongComputation inside the BackgroundWorker, the result doesn't show up.
So I tried a third time by using the flowing code:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
Dispatcher.Invoke(((Action)(() => Status.Text = args.Argument as string)));
};
worker.RunWorkerAsync(newStatus);
I was hoping that putting the update in a another thread would work. But it didn't.
What can I do to make sure that the status reflects the correct program state?