继续侦听SQLDependency

时间:2016-04-15 08:58:20

标签: c# entity-framework sqldependency

我有一个Windows窗体应用程序使用Notifier捕获SQLDependency更改事件与Entity Framework,一切正常。 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

感谢所有

1 个答案:

答案 0 :(得分:1)

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

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

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);
    }
}