c# - System.Threading.TimerCallback 仅在使用 Entity Framework 时触发一次

标签 c# winforms entity-framework timer

<分区>

我正在开发一个简单的应用程序,每 60 秒检查一次数据库。我使用 System.Threading.TimerCallback 来执行此操作,但是,当我运行该应用程序时,它只跳动一次。

代码如下:

private void Form1_Load(object sender, EventArgs e)
    {
        // Create the delegate for the Timer type. 
        System.Threading.TimerCallback timeCB = new System.Threading.TimerCallback(d);

        // Establish timer settings. 
        System.Threading.Timer t = new System.Threading.Timer(
          timeCB,     // The TimerCallback delegate object. 
          null,       // Any info to pass into the called method (null for no info). 
          0,          // Amount of time to wait before starting (in milliseconds). 
          1000);      // Interval of time between calls (in milliseconds). 
    }

    void m(object o)
    {
        System.Media.SystemSounds.Hand.Play();
        SReminderEntities ctx = new SReminderEntities();

        var jobs = (from m in ctx.Messages
                    select m).ToList();

        var seljobs = from j in jobs
                      where j.RemindeTime.Date == DateTime.Now.Date
                            && j.RemindeTime.Hour == DateTime.Now.Hour
                            && j.RemindeTime.Minute == DateTime.Now.Minute
                      select j;

        foreach (var j in seljobs)
        {
           // SendGmail("iReminder", j.Text, new string[] { j.User.Email }, "iReminderSender@Gmail.com");
            //this.sendSMS(j.User.Mobile, j.Text);
            System.Media.SystemSounds.Hand.Play();
        }//foreach
    }

    void d(object o)
    {
        MessageBox.Show("Test");
    }

当我调用 d 时它工作,但是 m 只运行一次。问题是什么,我该如何解决?谢谢。

最佳答案

System.Threading.Timer 类要求您维护自己对它的引用。它本身没有任何可以保持实例可访问的根数据结构。因此,如果您自己不保留引用,垃圾收集器将回收该对象,丢弃您的计时器。

尝试在您的表单类中创建一个私有(private)实例字段并将引用存储在那里。

另见 the documentation ,部分内容如下:

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

关于c# - System.Threading.TimerCallback 仅在使用 Entity Framework 时触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133965/

相关文章:

.net - 使用 DataContractSerializer 和 MetaDataTypeAttribute 问题自动生成 POCO 序列化

c# - 构建大字符串(例如 SQL 命令)C# 编译器有多聪明?

c# - 在存储过程调用中使用默认参数

c# - 将音频输入转换为时间并使用C#显示

C# WinForms,在运行时动态添加用户控件并且控件不可见?

c# - 如何处理System.Data.Entity.Validation.DbEntityValidationException?

c# - 数据集更新与 SQL 查询

c# - OpenFileDialog 的初始目录

c# - 如何在C# Winform 中设置每次加载的列表?

c# - Entity Framework : How to insert data while looping through multiple lists