Redaa
Redaa

Reputation: 1590

Properly use Background Worker in a WPF application

i'm stuck in using properly the background worker, the app needs to communicate with the database, so it takes a bit longer and the UI freezes for a while, i need to create a function that does the database things and wait until the work is finished, for this time, i want to display a kind of window that inform the user about the app state (Loading, busy, Downloading).

My code

i didn't write any code yet, but here're what i need:

//instructions
InitializeComponent();

//do this in background and wait until it finnishes
GetEntitiesFromDatabase();

entitiesListView.ItemSource = someList; (GetEntitiesFromDatabase will initialize this list)
//....

How can i proceed, i know that this question might be already asked in the forum but i'm desperate by searching for an answer, if this can be done other way please help me, thanks in advance.

Upvotes: 0

Views: 103

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61379

If you are going to directly manipulate the UI like that, you need to use Dispatcher.BeginInvoke when you aren't on the UI thread (read, in the BackgroundWorker).

Dispatcher.BeginInvoke(new Action(() =>
{
   entitiesListView.ItemSource = someList;
}), null);

You could also bind that items source to your view model (a much better idea) and the framework will marshal the change to the bound property for you.

Basically, either use Dispatcher.BeginInvoke or switch to MVVM (which WPF was meant to use anyways).

Upvotes: 2

Related Questions