As per the title. I click my button, and can enter the debugger at a breakpoint placed on the line calling openPicker.PickSingleFileAsync() – but this call never returns. I can select a file, and click Open, but I never get back into my method to actually do something with that file. This is all in a new Windows Metro ‘Blank Application’ with nothing but a Button and an Image.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFile().Wait();
}
private async Task OpenFile()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
// can break on following line
var file = await openPicker.PickSingleFileAsync();
// this line is never reached
if (file != null)
{
// do stuff
}
}
This is as per the sample code on MSDN here. I get the same result when I use PickMultipleFilesAsync as well.
Am I missing something obvious?
You should never mix
Wait()andawaitin a GUI application, because it can very easily lead to deadlocks, exactly as you are experiencing.For that matter, you probably shouldn’t use
Wait()at all, if you can useawait(although there are exceptions: it makes sense to useWait()in theMain()method of a console application that usesawait).The problem here is that
Wait()blocks your UI thread. After the file picker is done, it schedules the rest of the method to run on the UI thread, but the thread can’t do that because it’s waiting for this operation to complete. So, for this operation to complete, it first has to complete, which is a deadlock.The solution here is use
awaitin your event handler too: