I have app that uses UI thread and another thread for executing operations in background, and updates UI with results from those operations.
This all works well. However, during one operation I need to ask from user to enter some value. Sequence:
- UI thread running
- Command -> 2nd thread started (lets call it working thread) that works in background
- Working thread sends status information to UI while executing operations in sequence
- During one particular operation, Working thread is stopped
- A message is send that view must be shown, in order user to select an option
- UI thread subscribed to this type of message, so it displays a view
- User completes selection, and closes the view
- working thread receives user selection, and continues with execution
- Working thread finishes
Code to start new thead:
Thread thread = new Thread(Convert);
thread.SetApartmentState(ApartmentState.STA); // avoid "The calling thread must be STA" exception
thread.Start();
Code to send status information from working thread to UI thread:
Application.Current.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
(Action<OperationStatus>)delegate(OperationStatus operation)
{
OperationList.Add(operation);
}, status);
Code to ask user for confirmation:
In MainViewModel, during the execution of working thread:
// create ViewModel, that will be used as DataContext for dialog view
var vm = new SelectOptionViewModel(OptionList);
// subscribe to Close event, to get user selection
vm.Close += (s, e) =>
{
_option = vm.SelectedOption;
};
AppMessages.DialogScreen.Send(vm);
In MainView, during the execution of working thread:
AppMessages.DialogScreen.Register(this, vm =>
{
SelectOptionView view = new SelectOptionView();
view.DataContext = vm;
// view.Owner = this; // raises exeption about cross-threading
view.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
view.ShowDialog();
});
The problem is how to set the dialog view to be displayed as centered in parent view (MainView)? Setrting view.Owner to "this" is not possible, since "this" is created on UI thread.
What should I change here to center dialog view in my app, while preserving the order of sequnce defined?