danbord
danbord

Reputation: 4076

BackgroundWorker to update GUI

In my Silverlight application, I have an operation that takes a couple seconds and strongly interacts with the GUI (creation of display objects in a big "for" statement)

At first I thought of using the BackgroundWorker to avoid freezing the interface. But I cannot update the GUI directly, so I used the Dispatcher.BeginInvoke, but it still freezes the interface (since the long actions are on the gui part).

What I'd want is display a BusyIndicator while it loads my objects but I want the user to be able to continue working while it loads.

What else can I do? Any suggestions?

Upvotes: 2

Views: 539

Answers (2)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47038

Creating UI items in the BackgroundWorker is just wrong. Creating UI elements requires switching back to the UI thread if run from a BackgroundWorker. That is just making things worse than creating them on the main thread.

I assume that lots of the work in the BackgroundWorker is not creating the elements but some additional processing that happens to create UI elements in the middle of everything else.
If that is the case you need to break out the actual generation of UI elements. Replace the generation of UI elements with dummy-classes that contains all specifications required to build all elements. Then you return that collection of specifications (the dummy-classes) and generate the actual elements in the BackgroundWorker.RunWorkerCompleted event.

Upvotes: 4

JaredPar
JaredPar

Reputation: 754735

Even a busy icon won't help you here. Busy icons, or any other graphics item, require the UI thread to pump messages in order to not "freeze" the UI. If your long running operations are running on the UI thread then even the busy cursor will "freeze".

You need to either

  1. Move the expensive long running logic to a background thread
  2. Break up the UI logic into chunks and let the UI refresh in between them.

Upvotes: 5

Related Questions