【问题标题】:Derived async delegate called twice派生的异步委托被调用了两次
【发布时间】:2014-07-01 17:42:55
【问题描述】:

我正在尝试重用我的自定义控件,覆盖派生控件中的一些事件处理程序。

代码如下:

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;
        IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

        inputFile = file;
        InputVideoElement.SetSource(stream, file.ContentType);

    }
}

public sealed partial class DerivedControl : ControlBase {

        public DerivedControl() {
            this.InitializeComponent();

            PickFileButton.Click += pickFile;
        }
//This handler called twice
protected async override void pickFile(object sender, RoutedEventArgs e) {
        base.pickFile(sender, e);
        //some other actions
}

当我尝试调试它时,我看到以下内容: 当我单击派生控件上的按钮时,它调用override void pickFile(),它调用基本实现。在基本方法pickFile() 中执行丰富var file = await picker.PickSingleFileAsync();,然后,派生处理程序pickFile() 第二次调用,动作重复直到var file = await picker.PickSingleFileAsync(); 再次,之后我得到System.UnauthorizedAccessException

与基本控制按钮相同的操作可以正常工作。可能是什么问题?提前致谢

【问题讨论】:

    标签: c# asynchronous windows-runtime async-await


    【解决方案1】:

    您添加了两次Click 事件处理程序:一次在DerivedControl 构造函数中,一次在ControlBase 构造函数中。

    如果您只想要一个处理程序(如我所料),只需在 DerivedControl 构造函数中删除订阅即可。您的覆盖方法仍将被调用,因为 ControlBase 构造函数中的订阅只是一个委托,它将虚拟调用该方法。

    【讨论】:

    • yeee,我刚刚看到,在这里查看代码时!清新的外观非常有用。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2017-06-23
    • 2013-11-22
    • 2011-02-07
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多