使用C#中的弱处理程序引发PropertyChanged事件时发生ExecutionEngineException

M. *_*ley 2 c# weak-references inotifypropertychanged executionengineexception

我正在尝试引发一个由弱事件处理程序(通过PropertyChangedEventManager)监听的PropertyChanged事件.出于某种原因,我在举起事件时遇到了ExecutionEngineException.

我的事件提升代码如下:

protected virtual void RaisePropertyChanged(string aPropertyName)
{
    var lHandler = this.PropertyChanged;

    if (lHandler != null)
    {
        // ExecutionEngineException is thrown here
        lHandler(this, new PropertyChangedEventArgs(aPropertyName));
    }

    return;
}
Run Code Online (Sandbox Code Playgroud)

我的处理代码如下:

public bool ReceiveWeakEvent(Type aManagerType, object aSender, EventArgs e)
{
    bool lHandled = false;

    if (aManagerType == typeof(PropertyChangedEventManager))
    {
        OnPropertyChanged(aSender, e as PropertyChangedEventArgs);
    }

    return lHandled;
}
Run Code Online (Sandbox Code Playgroud)

当我搜索此异常时,我没有得到任何有用的结果,并且异常本身不包含任何有用的信息!是什么导致了这个问题?

M. *_*ley 5

在引发PropertyChanged事件博客条目,向PrcutionEngineException的作者发布道具.他完美地描述了问题和解决方案,但由于某种原因,他的网页在网页搜索结果中看起来并不高.我想在这里发布问题和答案,以帮助更多遇到同样问题的人.

所以事实证明,如果从ReceiveWeakEvent返回,WeakEventManager将调用Environment.FailFast().false

多么阴险的虫子!我同意博客文章的引用:

这可能是我生命中见过的最荒谬的过度反应错误处理.

我的固定处理程序如下:

public bool ReceiveWeakEvent(Type aManagerType, object aSender, EventArgs e)
{
    bool lHandled = false;

    if (aManagerType == typeof(PropertyChangedEventManager))
    {
        OnPropertyChanged(aSender, e as PropertyChangedEventArgs);
        lHandled = true;
    }

    return lHandled;
}
Run Code Online (Sandbox Code Playgroud)