How to block the UI during asynchronous operations in WPF
asynchronous, backgroundworker, wpf
Solution
Your clickable controls should be bound to commands, and the commands should have `CanBeExecuted` return false when a background task is in progress. If you do this, the controls bound to those commands will automatically disable and enable themselves.
You can avoid duplicating a lot of code by creating a command class that implements the background-task-in-progress check, and then deriving all of your commands (except the cancel command, of course) from this class.
Problem
We have a WPF app (actually a VSTO WPF app). On certain controls there are multiple elements which, when clicked, load data from a web service and update the UI. Right now, we carry out these web requests synchronously, blocking the UI thread until the response comes back. This prevents the user clicking around the app while the data is loading, potentially putting it into an invalid state to handle the data when it is returned. Of course the app becomes unresponsive if the request takes a long time. Ideally, we'd like to have the cancel button active during this time, but nothing else. Is there a clever way of doing this, or will we have to switch the requests to execute asynchronously using backgroundworker and write something that disables all the controls apart from the cancel button while a request is in progress? edit: for actions we already expect to be long running (downloading a file etc.) we pop up a progress dialog window. The case in point is when you expect the action to be pretty fast (a couple of seconds at most) but occasionally take longer. In those circumstances, flashing up a whole window for a moment is a bit too distracting.