I am printing a pdf using the PrintAsync() function of a WebView2 controller. This pdf is being prepared behind the scenes, so the user might ask to print it before it is ready. For this scenario, I have hooked an event that fires when the async Task of the pdf being prepared finishes.
The following code is called in the UI to print the after the pdf is ready, but because it might be called from the other thread that fires the event, it must be invoked via the dispatcher. This seems to be working when called from the UI itself (i.e. if the pdf is already ready when the user clicks the button) but not when called from the event handler (PrintAsync returns in a split second and results in an empty 1-page pdf).
I have tried two versions after some googling:
//Version 1 with InvokeAsync and unwrapping.
private async Task printAll()
{
CoreWebView2PrintStatus printStatus = CoreWebView2PrintStatus.OtherError;
printStatus = await Dispatcher.InvokeAsync(async () =>
{
dummyWebView.Source = m_viewModel.renderedPdfForAllCalculations;
return await dummyWebView.CoreWebView2.PrintAsync(m_printAllPrintSettings);
}).Task.Unwrap();
if (printStatus != CoreWebView2PrintStatus.Succeeded)
{
// show message
}
}
// Version 2 with Invoke. In this scenario, PrintAsync returns almost immediately and results in an empty 1-page pdf.
private async Task printAll()
{
CoreWebView2PrintStatus printStatus = CoreWebView2PrintStatus.OtherError;
await Dispatcher.Invoke(async () =>
{
dummyWebView.Source = m_viewModel.renderedPdfForAllCalculations;
printStatus = await dummyWebView.CoreWebView2.PrintAsync(m_printAllPrintSettings);
});
if (printStatus != CoreWebView2PrintStatus.Succeeded)
{
// show message
}
}