views:

451

answers:

2

How do you handle slow operations in the Model-View-Presenter (or MVC or M-V-VM or whatever variant you are using)?

When you have a slow operation in WinForms or SWT/JFace or whatever desktop framework you are using, you have to run it on a background thread to avoid completely locking up the application. Where do you handle this?

I can see a couple of solutions, but I am not entirely happy with any of them:

  1. Have the view call always call the presenter on a background thread. That means that the view have to handle that all invocations from the presenter probably will come from a background thread.

  2. Have the view call the presenter on the main thread. The presenter will then have to call back into the view when performing a slow operation, so that it can be run in the background.

What do you usually do?

EDIT: I just saw this article: http://www.codeproject.com/KB/threads/ThreadedExecuter.aspx . It is basically an implementation of 2. Have anyone tried anything like this?

+1  A: 

Hi, the view could call the presenter from the main thread. The presenter then starts the operation in a worker thread. And the view (e.g. with a timer) polls the presenter from the main thread, to prevent callbacks into the view. Regards, tamberg

tamberg
Do you mean (1)? If the presenter is called on the main thread, the timer would not run, while the presenter is blocking the main thread. But that is an option, too, yes - I am just not certain that it is better than the other options. Have you tried it?
Rasmus Faber
See edited answer (we do exactly that in our UIs). Regards
tamberg
+1  A: 

I use a pretty similar approach to tamberg (i.e. using worker threads to do the processing).

The main difference is the interaction with the view and the presentation model, which holds extra state that the view directly binds to for behavior such as:

  • input disabling
  • progress updates (fairly trivial using BackgroundWorker)
  • completion notification

By putting the extra state in the presentation model instead of the view, I'm able to swap views (or what is the more common case, have two views point to the same presenter).

micahtan