C# 在实例为';无法到达
离开作用域后,线程C# 在实例为';无法到达,c#,multithreading,timer,garbage-collection,weak-references,C#,Multithreading,Timer,Garbage Collection,Weak References,离开作用域后,线程TimerTest.exe!TimerTest.TimeClass.Callback(对象状态)仍在运行 避免此类线程运行的最佳做法是什么? 我可以上课时课吗 添加析构函数 是否实现一种方法来处理计时器 小样本: using System; using System.Threading; namespace TimerTest { internal class Program { private static void Main(string[
TimerTest.exe!TimerTest.TimeClass.Callback(对象状态)
仍在运行
避免此类线程运行的最佳做法是什么?
using System;
using System.Threading;
namespace TimerTest
{
internal class Program
{
private static void Main(string[] args)
{
// just a scope
{
var timerClass = new TimerClass(1);
}
Console.ReadKey();
}
}
internal class TimerClass
{
private Timer timer;
public TimerClass(int i)
{
this.timer = new Timer(Callback, i, 500, 1000);
}
private void Callback(object state)
{
Console.Out.WriteLine("Timer: " + state);
}
}
}
在主线程中启动计时器时,实际上会在线程池中启动一个新线程 如果要实现IDisTable并使用like创建计时器类:
(using var timerClass = new TimerClass(1))
{
your code here....
}
在dispose方法中,您需要从计时器中删除引用,以便GC将收集此对象,因为不再有对此对象的引用
对我来说,最好的方法是使用IDispoe和
当达到点击量时,还可以在回调方法中从计时器中清除refenrce
关于弱引用-我不确定这种情况是否适合使用()的定义
,{}
通常不适用于计时器。在整个生命周期中,将作用域限定为一个方法是非常罕见的。在这个例子中,这是可行的,但这是人为的。@HenkHolterman是的,你说得对。。但是我的意思是在timerclass中处理计时器为了使这成为一个正确的测试,在Readkey之前添加一个GC.Collect()。但是,仍然可能存在调试/发布差异,并且很少有保证。