This is an old post, but I spend 2 days on the result that I want to present here (with a "context" and a complete but simplified code) @ Joshua's answer worked for me (finally when I believe in .ConfigureAwait (true), see First code example). Perhaps I was able to write fewer lines based on the long MSDN Threading Model article that I still need to read again.
My context is WPF (basic MVVM), and I have to select a file to write some backup .CSV (from datagrid). I need the (member) ChooseFileFromExtension() function to be asynchronous with a non-blocking FileDialog
class MainWindowExportToExcelCSV : ICommand { ... public async void Execute(object parameter) { var usr_ctrl = parameter as UserControl; MyFileDialog fd = new MyFileDialog(); const bool WhenIComeBackIStillNeedToAccessUIObjectAndThusINeedToRetrieveMyOriginalUIContext = true; string filename = await fd.ChooseFileFromExtension("CSV files (*.csv)|*.csv|All files (*.*)|*.*").ConfigureAwait( WhenIComeBackIStillNeedToAccessUIObjectAndThusINeedToRetrieveMyOriginalUIContext); Visual visual = (Visual)usr_ctrl.Content; for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++) {
and class code MyFileDialog
using Microsoft.Win32; ... class MyFileDialog {
fetcher.BeginInvoke() launches (asynchronously) SaveFileDialog ShowDialog() on another thread, so that the main thread / user interface window (... ++) is not blocked and is not blocked, as it would with a simple direct call ShowDialog() . TaskCompletionSource<string> tcs not a WPF interface object, so its access to another "single" thread is fine.
This is another field that I need to study further. I feel that there is no βfinalβ documentation / book on this subject (maybe you need to look again at books like the ones Steven Cleary had). This code should be improved, at least with the c-sharp-aynchronous-call-without-endinvoke theme
It works with Microsoft.Win32 FileDialog namespace
NGI Feb 28 '17 at 15:52 2017-02-28 15:52
source share