继续监听 SQLDependency

Continue listening for SQLDependency

我有一个 Windows 表单应用程序,它使用通知程序来捕获带有 Entity Framework 的 SQLDependency 更改事件,并且一切正常。 EntityChangeNotifier 是一个详细说明 SQLDependency 的项目。

打完电话 while (true) 我可以继续收听,当我更改代码时输入 notifer.Changed += (sender, e)

        private StartNotifier()
        {
            var info = new SABIntegrationEntities();
            // Notifier
            using (var notifer = new EntityChangeNotifier<SpRicezioneSpedizioniLightNotifier, GemapDbContext>(p => p.SPEDIZIONE_STATO_GENERAZIONE == "I" || p.SPEDIZIONE_STATO_GENERAZIONE == "U"))
            {
                notifer.Error += (sender, e) =>
                {
                    Log.Error(String.Format("[{0}, {1}, {2}]:\n{3}", e.Reason.Info, e.Reason.Source, e.Reason.Type, e.Sql));
                };
                notifer.Changed += (sender, e) =>
                {
                    e.ContinueListening = false;
                    bool result = true;
                    var spedizioniI = info.SpRicezioneSpedizioniLights.Where(x => x.SPEDIZIONE_STATO_GENERAZIONE == "I" || x.SPEDIZIONE_STATO_GENERAZIONE == "U");
                    foreach (var p in spedizioniI)
                        {
                            p.SPEDIZIONE_STATO_GENERAZIONE = "G";
                        }
                    }
                    e.ContinueListening = true;
                };
                while (true)
                {
                }
           }
       }

与 While(true) 相比,我希望继续收听此代码。我该怎么做?

如果需要,可以在此处找到完整的项目结构:enter link description here

感谢大家

当您退出 StartNotifier 方法时,您的 using 语句正在释放 notifer。删除 using 和 while 语句,将 notifer 作为私有 class 字段,实现 IDisposable 接口并在 Dispose 方法中处理 notifer。在包含 StartNotifier 方法的 class 未被处理之前,您应该会收到消息。

编辑:给你一个想法的代码片段:

public partial class Form1 : Form
{
    private readonly EntityChangeNotifier<SpRicezioneSpedizioniLightNotifier, GemapDbContext> _entityChangeNotifier;
    public Form1()
    {
        InitializeComponent();
        _entityChangeNotifier = StartNotifier();
    }

    private EntityChangeNotifier<SpRicezioneSpedizioniLightNotifier, GemapDbContext> StartNotifier()
    {
        var notifer = new EntityChangeNotifier<SpRicezioneSpedizioniLightNotifier, GemapDbContext>(
            p => p.SPEDIZIONE_STATO_GENERAZIONE == "I" || p.SPEDIZIONE_STATO_GENERAZIONE == "U");
        notifer.Error += (sender, e) => { /*log*/ };
        notifer.Changed += (sender, e) => { /*action when chagned*/};
        return notifer;
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
            _entityChangeNotifier.Dispose();
        }
        base.Dispose(disposing);
    }
}