Wpf
I am attempting to delay window closing until all tasks are completed using the async/await library of StephenCleary https://github.com/StephenCleary/AsyncEx.
The event handler delegate and event arguments definitions:
public delegate void CancelEventHandlerAsync(object sender, CancelEventArgsAsync e);
public class CancelEventArgsAsync : CancelEventArgs
{
private readonly DeferralManager _deferrals = new DeferralManager();
public IDisposable GetDeferral()
{
return this._deferrals.GetDeferral();
}
public Task WaitForDefferalsAsync()
{
return this._deferrals.SignalAndWaitAsync();
}
}
Then in the code behind of the NewWindowDialog.xaml, I override the OnClosing event:
public NewWindowDialog()
{
InitializeComponent();
}
protected override async void OnClosing(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
base.OnClosing(e);
await LaunchAsync();
}
private async Task LaunchAsync()
{
var vm =(NewProgressNoteViewModel)DataContext;
var cancelEventArgs = new CancelEventArgsAsync();
using (var deferral = cancelEventArgs.GetDeferral())
{
// a very long procedure!
await vm.WritingLayer.CompletionAsync();
}
}
Clearly, this fails since e.Cancel = true is executed before the await. So what am I missing to correctly use GetDeferral() to delay the window closing while the tasks are being completed (in WPF).
TIA
Edit: With the help of everybody, I am currently using this. However, does anybody have a good example of the Deferral pattern on window closing?
Thanks to all.
private bool _handleClose = true;
protected override async void OnClosing(System.ComponentModel.CancelEventArgs e)
{
using (new BusyCursor())
{
if (_handleClose)
{
_handleClose = false;
IsEnabled = false;
e.Cancel = true;
var vm = (NewProgressNoteViewModel)DataContext;
await vm.WritingLayer.SaveAsync();
e.Cancel = false;
base.OnClosing(e);
}
}
}