gab*_*jcs 4 c# filepicker async-await microsoft-metro storagefile
我的代码到底有什么问题?
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker FilePicker = new FileOpenPicker();
FilePicker.FileTypeFilter.Add(".exe");
FilePicker.ViewMode = PickerViewMode.List;
FilePicker.SuggestedStartLocation = PickerLocationId.Desktop;
// IF I PUT AWAIT HERE V I GET ANOTHER ERROR¹
StorageFile file = FilePicker.PickSingleFileAsync();
if (file != null)
{
AppPath.Text = file.Name;
}
else
{
AppPath.Text = "";
}
}
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
无法将类型'Windows.Foundation.IAsyncOperation'隐式转换为'Windows.Storage.StorageFile'
如果我添加'await',就像在代码上发表评论一样,我收到以下错误:
¹"await"运算符只能在异步方法中使用.考虑使用'async'修饰符标记此方法并将其返回类型更改为'Task'.
代码源在这里
好吧,编译错误消息直接解释了代码无法编译的原因.FileOpenPicker.PickSingleFileAsync返回IAsyncOperation<StorageFile>- 所以不,你不能将该返回值StorageFile赋给变量.IAsyncOperation<>在C#中使用的典型方法是使用await.
您只能await在async方法中使用...所以您可能希望将方法更改为异步:
private async void BrowseButton_Click(object sender, RoutedEventArgs e)
{
...
StorageFile file = await FilePicker.PickSingleFileAsync();
...
}
Run Code Online (Sandbox Code Playgroud)
请注意,对于除事件处理程序之外的任何内容,最好使异步方法返回Task而不是void- 使用的能力void实际上只是因为您可以使用异步方法作为事件处理程序.
如果你不是真正熟悉async/ await然而,你或许应该阅读起来就可以了,你走之前的任何进一步的-在MSDN"与异步异步编程和等待"页面可能是一个不错的起点.