[WPF] InteractionRequest.RaiseAsync not quite correct
Package info
- Platform: WPF
- Prism version: 6
Although it is declared as asynchronous returning Task, actually it blocks.
Repro steps
var task = interactionRequest.RaiseAsync(notification);
// some other code
await task;
Some other code is not executed until the popup window is closed, if the popup is modal.
RaiseAsync goes as this:
var tcs = new TaskCompletionSource<TResult>();
f(n => tcs.SetResult(n));
return tcs.Task;
where f is callback => this.Raise(context, callback)
Thus, Raise() raises the event to which PopupWindowAction is hooked which executes wrapperWindow.ShowDialog() and this does not return, hence return tcs.Task; is not executed.
A correction might look like
var tcs = new TaskCompletionSource<TResult>();
var task = Task.Factory.StartNew(() => f(n => tcs.SetResult(n)),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
return tcs.Task;
This is the idea. For production code, need to propagate exceptions from task to tcs.Task.
@wldevries You may be interested in this.
Since WPF is always running on the dispatcher we could also do the following:
var tcs = new TaskCompletionSource<TResult>();
var dispatcherTask = Dispatcher.BeginInvoke(() => f(n => tcs.SetResult(n)));
return Task.WhenAll(dispatcherTask, tcs);
Note that you need to add a reference to System.Windows.Presentation for this Dispatcher extension method.
Okay tried to be smart to avoid the warning about not awaiting BeginInvoke with WhenAll, but this will of course not return the correct result. It should be the following with a pragma to ignore the warning.
var tcs = new TaskCompletionSource<TResult>();
var dispatcherTask = Dispatcher.BeginInvoke(() => f(n => tcs.SetResult(n)));
return tcs;
@wldevries
- Direct use of Dispatcher makes it very difficult to write tests. Synchronization context is easier to control.
- Actually, CallbackHelper.AwaitCallbackResult is very nice and may have usages in a lot of other places. I would even make it public. It works well for almost all cases except for Raise which is actually blocking. Thus, I would prefer to leave AwaitCallbackResult without modification and implement RaiseAsync without the use of AwaitCallbackResult.
- Ignoring the task completely will eat up exceptions.
@wldevries What do you think?
I think you're probably right, but I haven't had a practical go at it yet.
I don't use unit tests often and that's why I usually use the dispatcher directly which is neater code as you can see.
@wldevries It's neater only because it does not handle exceptions. If the popup window crashes the user has no chance to catch the crash.
@wldevries Simplified it :)
@wldevries Added an option to execute the old variant - sometimes it is needed. E.g.:
A program has a method to check whether a document is modified and popup a window suggesting the user to save it. The user may confirm or refuse.
This method may be called in two places: when a user closes a document to open a new one; and also we may have a hook into [x] button of the program window (Window.Closing event). In the hook we would call the same method and return true/false, allowing/not allowing to close the window.
But Window.Closing callback should be executed synchronously and provide true/false value before returning.
Now the method may be written having the executeSynchronously parameter, defaulting to false. This allows to use the method in the program normally and to unit test it. From the Window.Closing callback the method will be called with executeSynchronously = true.
Sample code.
public async Task<bool> CheckForUnsaved(bool executeSynchronously)
{
if (!HasChanges())
{
return true;
}
CheckForUnsavedNotification notification = await this.InteractionRequest.RaiseAsync(new CheckForUnsavedNotification(), executeSynchronously);
switch (notification.Selection)
{
case Selection.Cancelled:
return false;
case Selection.Save:
await SaveAsync(executeSynchronously);
return true;
case Selection.DiscardChanges:
return true;
}
}
public async Task OnNewDocument()
{
if (await CheckForUnsaved(false)) //
{
// initialize new document
}
}
public void OnWindowClosing(object sender, CancelEventArgs args)
{
args.Cancel = !CheckForUnsaved(true).Result;
}
Note that
public async void OnClosing(object sender, CancelEventArgs args)
{
args.Cancel = !await CheckForUnsaved(false);
}
will close the window because it returns before CheckForUnsaved completed.
And
public void OnWindowClosing(object sender, CancelEventArgs args)
{
args.Cancel = !CheckForUnsaved(false).Result;
}
will deadlock because CheckForUnsaved will attempt to run code on the GUI thread which is blocked by accessing the Result property.
Thus, without this little trick with executeSynchronously argument you will need a separate, all-synchronous variant of CheckForUnsaved, including the Save method.
The behavior of CheckForUnsaved method is pretty unit testable using a mock event handler for Raise event.
@brianlagunas If the sample does not convince you, you decide what to do: there is already a (in fact, synchronous) version of @wldevries, and there is an asynchronous version which is called now RaiseImplAsync.
- Leave wldevries and remove this PR.
- Replace wldevries version by RaiseImplAsync
- Have both versions under different names (from which I will be able to construct the method I need).
I am actually leaning towards removing this altogether and noting it as a breaking change in the next major release.. I should have personally tested this thoroughly before excepting the PR, and that was my fault.
@brianlagunas I agree that it is better to remove the current half-baked async implementation than leaving it.
However, the case of RaiseAsync is one of the most difficult ones in the async world due to the nature of Dispatcher UI thread and blocking ShowDialog call with its nested message loop. I would prefer that Prism provide some solution to this rather than leaving users on their own.
I agree, as is proven by my half baked PR ;-)
@wldevries Agree with what? ;-)
I agree that pulling the current implementation until we have one that we are happy with is the right way to go. Also echo @dvorn comment - we should not be doing this with Dispatcher directly because it blocks testability, need to use SynchronizationContext instead because it is at least mockable (with non-trivial effort). You can take a look at the implementation of PubSubEvent
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.