【发布时间】:2015-06-17 20:57:15
【问题描述】:
离开作用域后,线程TimerTest.exe!TimerTest.TimeClass.Callback(object state) 仍在运行。
避免此类运行线程的最佳做法是什么?
- IDisposable 类 TimerClass?
- 添加析构函数?
- 实现一个方法来处理定时器?
小样本:
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);
}
}
}
【问题讨论】:
-
要使其成为正确的测试,请在 Readkey 之前添加 GC.Collect()。但是仍然可能存在调试/发布差异,并且很少有保证。
标签: c# multithreading timer garbage-collection weak-references