等待派生事件处理程序中的基本方法的执行

时间:2014-07-02 07:35:30

标签: c# .net event-handling async-await

我试图在派生自定义控件中获取文件属性。代码如下:

    public partial class ControlBase : UserControl {
public ControlBase() {
        this.InitializeComponent();
        //Buttons
        PickFileButton.Click += pickFile;
}

protected virtual async void pickFile(object sender, RoutedEventArgs e) {

    var picker = new FileOpenPicker();
    picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
    picker.FileTypeFilter.Add(".wmv");
    picker.FileTypeFilter.Add(".mp4");

    var file = await picker.PickSingleFileAsync();

    if (file == null) return;
    inputFile = file;
    }
}

public sealed partial class DerivedControl : ControlBase {

protected async override void pickFile(object sender, RoutedEventArgs e) {
        base.pickFile(sender, e);
        //need to pick file first
        var properties = await inputFile.Properties.GetVideoPropertiesAsync();
}

我如何等待picker.PickSingleFileAsync()完成?已经选择了派生实现继续befor文件。提前谢谢!

2 个答案:

答案 0 :(得分:3)

由于await async void protected virtual async void pickFile(object sender, RoutedEventArgs e) { await PickFileAsync(); } protected async Task PickFileAsync() { var picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.FileTypeFilter.Add(".wmv"); picker.FileTypeFilter.Add(".mp4"); var file = await picker.PickSingleFileAsync(); if (file == null) return; inputFile = file; } ,我建议您以可以等待的方式进行此操作:

protected async override void pickFile(object sender, RoutedEventArgs e) 
{
    await base.PickFileAsync();

    //need to pick file first
    var properties = await inputFile.Properties.GetVideoPropertiesAsync();
 }

然后在你的派生中:

inputFile

我认为您的派生类型中可以访问Task<InputFile>。如果没有,只需从PickFileAsync

返回{{1}}即可

答案 1 :(得分:0)

也许你在 base.PickFile(发件人,e)前面缺少await关键字?