C# Call class using System.Threading.Timer from Winforms interval 失败

C# Call class using System.Threading.Timer from Winforms interval fails

我有一个使用其他 class(在分离的 DLL 中)的 winform 应用程序 它看起来像:

public Form1()

    {

        foo = new Foo(2500, this.refreshGrid);
     }
    private void refreshGrid(List<int> source)
    {
        dgvDrivers.AutoGenerateColumns = true;
        dgvDrivers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        dgvDrivers.SynchronizedInvoke(() => dgvDrivers.DataSource = source);
        dgvDrivers.AutoResizeColumns();
     }

和扩展方法:

   public static void SynchronizedInvoke(this ISynchronizeInvoke sync,  Action action)
    {
         // If the invoke is not required, then invoke here and get out.
          if (!sync.InvokeRequired)
           {
               // Execute action.
               action();

              // Get out.
               return;
           }

           // Marshal to the required context.
          sync.Invoke(action, new object[] { });
       }

现在我有一个 class 可以在特定时间将新 System.Threading.Timer 初始化为 运行 一次:

public CreateTimer(int dueTime)
{
      new System.Threading.Timer(SchudleStatusChange, null, dueTime, System.Threading.Timeout.Infinite);
  }

返回 UI - 有一个按钮每次点击调用 CreateTimer() 10 次 但是定时器被调用的次数比我预期的要少。 我想这与使用 winforms 和调用主线程有关。

有什么想法吗?

您没有挂起对计时器的引用,因此垃圾收集器吞噬了它并将其关闭。

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.