2

Is it any easier to do background work with the UI in WPF?

It's such a pain with WinForms, and would like an easier way. I want to do database work, and as it's doing database work, I want to populate a control with results returned from the database as it happens, and after it's done.

1
  • We have been using BackgroundWorker successfully in WinForms for many years and have not found it a "pain". If you are having problems with it, post your code in a question and we can take a look. Commented Oct 22, 2012 at 17:21

2 Answers 2

1

Here's a code example:

private void RunButton_Click(object sender, RoutedEventArgs e) { ThreadPool.QueueUserWorkItem( delegate { // Do work Dispatcher.Invoke(new Action( delegate { // Do UI stuff })); // Do more work Dispatcher.Invoke(new Action( delegate { // Do UI stuff })); }); } 

Note however that if an exception is thrown while on the background thread, the application will terminate. You should catch exceptions on a background thread, and re-throw them on the UI thread (again using Dispatcher).

Sign up to request clarification or add additional context in comments.

Comments

1

As in WinForms in WPF changes to UI control need to be made on the UI thread. However in a way with data binding it can become easier to manage. For example if you bind your UI to certain properties then you can change those from other threads and the binding will take of the rest. With collections it becomes a bit more tricky but there are thread safe observable collection implementations out there and in .Net 4 there are some included in the framework. Also the BackgroundWorker class might be of interest to you.

7 Comments

Thanks! The backgroundworker class scared the hell out of me in WinForms! I thought I was all set! But no, I wasn't. It just never updated the UI.
What was the problem in using BackgroundWorker??
To be honest I never used the background worker class. I always have gotten away with either firing off async operations to the thread pool with either BeginInvoke or explicit enqueuing or used a constantly running thread with a work item queue.
Hmmm, BeginInvoke and constantly running thread with a work item queue look interesting. I'll look into them, I've never heard of them before.
@ferosekhanj - The problem I kept having was that I read in the MSDN docs that you need to do the UI work inside the ProgressChanged, but even though I was doing that, nothing was visually-happening on the UI, and values weren't even being assigned to strings inside the progresschanged event either. After about a month I just gave up on it. Had to move on and find a workaround.
|