[英]C# Call class using System.Threading.Timer from Winforms interval fails
i have a winform app that uses other class(in seprated DLL) it looks like: 我有一个使用其他类的Winform应用程序(在单独的DLL中),它看起来像:
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();
}
and the Extension method: 和扩展方法:
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[] { });
}
now i have a class that init new System.Threading.Timer to run once at specfic time: 现在我有一个初始化新System.Threading.Timer的类,以在特定时间运行一次:
public CreateTimer(int dueTime)
{
new System.Threading.Timer(SchudleStatusChange, null, dueTime, System.Threading.Timeout.Infinite);
}
Back to UI - there is button that calls CreateTimer() 10 times per click but the timer is invoked less times then i expected. 返回UI-有一个按钮,每次单击可调用CreateTimer()10次,但调用计时器的次数少于我期望的次数。 I guess it something realted to using winforms and the invoke of main thread. 我猜想这确实与使用winforms和主线程的调用有关。
any ideads? 有想法吗?
You didn't hang on to a reference to your timer, so the garbage collector gobbled it up and shut it down. 您没有停留在对计时器的引用上,因此垃圾收集器将其吞噬并关闭了。
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. 计时器仍处于活动状态并不妨碍其被收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.