簡體   English   中英

ICommand實現定期引發COM異常

[英]ICommand implementation throws COM Exception regularly

我正在使用MVVM模式構建UWP應用。 我已經實現了本書中提到的ICommand接口:“ Microsoft Visual C#2013-分步指南”。

ICommand的實現:

public class Command : ICommand
    {
        private Action _methodToExecute;
        private Func<bool> _methodCanExecute;

        public Command(Action methodToExecute) : this(methodToExecute, null)
        {
        }

        public Command(Action methodToExecute, Func<bool> methodCanExecute)
        {
            _methodToExecute = methodToExecute;
            _methodCanExecute = methodCanExecute;

            var dt=new DispatcherTimer();
            dt.Tick += (s, e) => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
            dt.Interval = new TimeSpan(0, 0, 1);
            dt.Start();
        }

        public bool CanExecute(object parameter) => _methodCanExecute == null ? true : _methodCanExecute();

        public void Execute(object parameter) => _methodToExecute();

        public event EventHandler CanExecuteChanged;
    }

每3-4分鍾運行一次,應用崩潰並顯示COM異常。

    System.Runtime.InteropServices.COMException was unhandled by user code
  ErrorCode=-2147467259
  HResult=-2147467259
  Message=Error HRESULT E_FAIL has been returned from a call to a COM component.
  Source=mscorlib
  StackTrace:
       at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
       at System.Runtime.InteropServices.WindowsRuntime.ICommandAdapterHelpers.<>c__DisplayClass2.<CreateWrapperHandler>b__3(Object sender, EventArgs e)
       at FavQuotesMain.ViewModels.Command.<.ctor>b__3_0(Object s, Object e)
  InnerException: 

構建Win 8.1應用程序時未發生此異常。 請提供建議以刪除此異常。

dt.Tick += (s, e) => CanExecuteChanged?.Invoke(this, EventArgs.Empty);

這很可能是造成您問題的原因。 我不確定為什么要向您的CanExecuteChanged發送垃圾郵件,但是也許您想重新考慮一下您的執行模型。

另外,我們也不知道您的代表正在調用什么方法。 因此,失敗的原因可能有很多。

我想你的問題是計時器。

我總是像這樣實現ICommand:

public class Command : ICommand
{
    private readonly Action<object> execute;
    private readonly Predicate<object> canExecute;

    public Command(Action<object> execute, Predicate<object> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public void Execute(object parameter)
    {
        execute(parameter);
    }

    public bool CanExecute(object parameter)
    {
        return canExecute == null || canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}

@Water解決方案是在我們希望View知道Control的更改狀態時手動引發CanExecuteChanged

腳步:

  1. 將CanExecuteChanged包裝到類似OnCanExecuteChanged ()的方法中
  2. 從相關的ViewModel屬性設置器調用此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM