相关疑难解决方法(0)

定时器可以自动收集垃圾吗?

当您使用a Timer或者Thread只运行程序的整个生命周期时,您是否需要保留对它们的引用以防止它们被垃圾回收?

请放下以下程序可以timer作为类中的静态变量的事实,这只是一个展示问题的玩具示例.

public class Program
{
    static void Main(string[] args)
    {
        CreateTimer();

        Console.ReadLine();
    }

    private static void CreateTimer()
    {
        var program = new Program();

        var timer = new Timer();
        timer.Elapsed += program.TimerElapsed;
        timer.Interval = 30000;
        timer.AutoReset = false;
        timer.Enabled = true;
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        var timerCast = (Timer)sender;

        Console.WriteLine("Timer fired at in thread {0}", GetCurrentThreadId());

        timerCast.Enabled = true;
    }

    ~Program()
    {
        Console.WriteLine("Program Finalized");
    }

    [DllImport("kernel32.dll")]
    static extern uint GetCurrentThreadId(); …
Run Code Online (Sandbox Code Playgroud)

c# multithreading garbage-collection timer

24
推荐指数
2
解决办法
6833
查看次数

标签 统计

c# ×1

garbage-collection ×1

multithreading ×1

timer ×1