在作为服务运行时不会触发事件

Tim*_*Tim 5 c# service events delegates

我有一个在测试模式下运行时运行正常的事件,但是当我将代码作为服务运行时不会触发.在我发布代码之前,让我为应用程序提供一些结构,因为我觉得这就是问题所在.

我有一个托盘应用程序,用于控制路由器服务.启动时,服务会加载一个dll库,进行所有处理.启动库时,它会扫描目录中的插件,并将它们挂钩到主程序中.

当构建为Release时,服务被激活,我必须安装该应用程序.作为旁注,托盘应用程序以管理员身份运行,因此可以控制服务.构建为Debug时,托盘会直接启动库dll,跳过启动它的小型服务应用程序.见下图:

在此输入图像描述

在任何一种情况下,此插件的流程都是Receiver接收文件,并通知发件人通过事件转发它.该文件被发送以进行远程处理,然后返回到另一个Receiver,后者通过Event将结果转发给插件.然后插件处理该文件,并应在事件中发送回主程序.在Debug(无服务)中运行时,这正是发生的事情.作为服务运行时,除了通知主程序处理结果的插件外,所有事件处理都能正常工作.没有抛出异常,我已通过记录确认事件已正确连接.

连接活动:

//  Connect delegate to plugins that will add data to the database through the Router
if (plugin is INotify)
{
    ((INotify)plugin).NotifyProcessingComplete += new ProcessNotification(this.OnProcessed);
    LogWriter.Log("Associated " + plugin.Name + " with OnProcessed", LogFile);
}
Run Code Online (Sandbox Code Playgroud)

从插件中调用事件:

if (NotifyProcessingComplete != null)
    NotifyProcessingComplete(ExtractResults(args.ReceivedFile));
else
    LogWriter.Log("NotifyProcessingComplete Delegate was null.", LogFile);
Run Code Online (Sandbox Code Playgroud)

事件处理程序:

public void OnProcessed(ProcessArgs args)
{
    LogWriter.Log("On Dicom Process was called...", LogFile);
    lock (threadLock)
    {
        if (Settings != null)
        { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)

根据日志,插件正确连接到OnProcessed,并且登录ExtractResults()方法显示它正确返回.但是,NotifyProcessingComplete不会调用OnProcessed方法.

再一次,只有在将代码作为服务运行时才会发生这种情况.我怀疑它可能与以管理员身份运行的托盘,以本地系统运行的服务以及动态加载的插件有关.

下面我已经包含了我加载插件的代码,以防它可能会有所帮助:

private void loadPlugins()
{
    String pluginPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    //  Create a domain to text for plugins
    AppDomain domain = AppDomain.CreateDomain("PluginLoader");

    PluginFinder finder = (PluginFinder)domain.CreateInstanceAndUnwrap(
        typeof(PluginFinder).Assembly.FullName, typeof(PluginFinder).FullName);
    finder.LogFile = logFile;

    //  Get valid plugins, and then unload the domain to clear up memory
    List<String> FoundPluginTypes = finder.SearchPath(pluginPath);
    AppDomain.Unload(domain);

    //  Load the plugins
    Plugins = new List<IPlugin>();
    foreach (String plugin in FoundPluginTypes)
    {
        Assembly assembly = Assembly.LoadFrom(plugin);
        Type type = null;

        foreach (Type t in assembly.GetTypes())
            if (t.GetInterface("IPlugin") != null)
                type = t;

        try
        {
            IPlugin loader = (IPlugin)Activator.CreateInstance(type);
            Plugins.Add(loader);
        }
        catch (NullReferenceException e)
        {
            LogWriter.Log("Could not load plugin.", e, LogFile);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何帮助或建议将不胜感激.先感谢您.

Dha*_*alk 0

你能检查一下接收者/发送者对象是否没有被垃圾回收吗?可能是这种情况,因为发布和调试的初始化模式不同