Caliburn.Micro icon indicating copy to clipboard operation
Caliburn.Micro copied to clipboard

PlatformProvider.Current not safe when there are multiple UI threads

Open EricGriffith opened this issue 7 years ago • 3 comments

When there are multiple UI threads, things that need to run on the UI thread must use the proper Dispatcher for invoking methods. Currently Screen.TryClose and the Execute.XXX methods all make use of the static PlatformProvider.Current property to find the Dispatcher to use. This results in exceptions being thrown when using windows on more than one UI thread.

I think this is related to issue #427.

EricGriffith avatar May 21 '17 16:05 EricGriffith

Yup, it's a quasi known issue that I'd love to get some feedback / help on. I assume your problem is with UWP and multiple windows?

The problem can be broken down to this.

  • When we want to dispatch an action to the UI thread how do we determine which UI thread to do it on?
  • There's no good way to determine on a view model which is the correct dispatcher as there's no affinity for them.
  • At the moment the best we do is "switch" the active dispatcher on Window Activation and also when dispatching to the UI thread we check if we're already on a UI thread.

What the above point allows is that you do the work to ensure your view model updates are on the correct UI thread then the framework won't get in your way.

I'm not sure if there's a grand unifying theory about how to correlate view models to dispatchers, except for things like capturing the dispatcher at creation (assuming the view model is created on the right thread).

Would love to get some feedback here.

nigel-sampson avatar May 22 '17 02:05 nigel-sampson

We were trying to use separate UI threads for the task pane and pop-up dialogs in an Office extension. We switched back to single-threaded and it's working fine now.

Can the dispatcher be determined for a view on construction?

EricGriffith avatar May 22 '17 12:05 EricGriffith

Ah interesting, hadn't considered Office extensions in regard to the check to see if we're on a UI thread before dispatching.

If that's already there or can be added then what you'll need to do is capture "correct" dispatcher at view model creation and do your own work.

Will do some research and add it here.

nigel-sampson avatar May 22 '17 23:05 nigel-sampson