尽管InvocationList包含订阅方法C#,但不调用EventHandler

时间:2016-07-05 12:49:51

标签: c# events mef eventhandler eventargs

我正在开发一个MEF应用程序。我使用插件作为发布者而另一个作为订阅者使用。对于当前问题,我保证两个插件实例都是活动的。在订阅者上我订阅了事件,在发布者上我遍历调用列表并调用BeginInvoke以异步方式引发事件:

出版商:

public class BackchannelEventArgs : EventArgs {
    public string Intensity { get; }
    public BackchannelEventArgs(string intensity) {
        this.Intensity = intensity;
    }
}

public class Publisher {
    public event EventHandler<BackchannelEventArgs> BackchannelEvent = delegate { };

    private void BackchannelEventAux(string bcintensity) {
        Plugin.LogDebug("BACKCHANNEL EVENT, sending to " + BackchannelEvent.GetInvocationList().Length + " subscribers: " + bcintensity);

        var args = new BackchannelEventArgs(bcintensity);
        foreach (EventHandler<BackchannelEventArgs> receiver in BackchannelEvent.GetInvocationList()) {
            receiver.BeginInvoke(this, args, null, null);
        }
    }
}

订阅者(相关片段,我正在通过pluginsManager调用Init,我可以在其中看到日志):

class Subscriber {

    public void Init(){
        LogInfo("Before subscribing");
        publisher.BackchannelEvent += HandleBackchannelEvent;
        LogInfo("After subscribing");
    }

    private void HandleBackchannelEvent(object sender, BackchannelEventArgs e) {
        LogDebug("Handle Backchannel!");
    }
}

现在,根本没有调用您在事件处理程序上看到的日志。我有4个其他事件遵循相同的结构,有些特别是没有调用此事件(我可以在其他事件上看到日志)。其他插件遵循完全相同的结构。

已经尝试过:

  • 同步调用BackchannelEvent(this, args)但结果相同;
  • 同样在其他插件上订阅同一个事件,但问题仍然存在于此单个事件上(而不是其他遵循相同结构的事件)。

我希望你能给我一些帮助。

谢谢

编辑:显示的代码是一个代码段。 pluginsManager正在调用Init方法。我在订阅电话之前写了一个日志,我可以确认我确实订阅了。

Edit2:InvocationList中的元素数实际上是2(空委托和订阅者),因此它会检出。

1 个答案:

答案 0 :(得分:0)

好。我不知道为什么,但我想出了解决方案,以便其他遇到问题的人可以找到解决方案。它与我为Random类创建的扩展相关(虽然它没有抛出异常......所以它可能是C#的一个bug,我无法解释)。随机扩展由我创建的外部NuGet包提供。

版本A(不使用随机扩展名):

EventHandler的正文:

LogDebug("Inside Handler");
double intensityValue2 = GetRandomNumber(Settings.MinimumIntensity, Settings.MaximumIntensity);
double frequency2 = GetRandomNumber(Settings.MinimumFrequency, Settings.MaximumFrequency);
int repetitions2 = GetRandomInt(Settings.MinimuMRepetitions, Settings.MaximumRepetitions);

版本B(使用随机扩展名):

EventHandler的主体:

LogDebug("Inside Handler");
double intensityValue2 = random.GetRandomNumber(Settings.MinimumIntensity, Settings.MaximumIntensity);
double frequency2 = random.GetRandomNumber(Settings.MinimumFrequency, Settings.MaximumFrequency);
int repetitions2 = random.GetRandomNumber(Settings.MinimuMRepetitions, Settings.MaximumRepetitions);

版本A是它正在使用的版本。保证显示日志。我不知道为什么它不让我使用扩展,但它现在已经解决了。如果随机扩展引发了异常,但事实并非如此......

如果有其他人偶然发现这个问题,我希望这可以帮助你更快地找出问题。

谢谢