为什么C#thread会自动停止工作

时间:2013-02-22 05:04:59

标签: c# multithreading

我的程序中有一个运行计时器功能的线程,例如

Thread PopMonitoringThread = new Thread(new ThreadStart(PopMonitoring));  
PopMonitoringThread.Start();

public static void PopMonitoring()
{
    TimerCallback callback = new TimerCallback(Tick);
    Timer stateTimer = new Timer(callback, null, 0, 1000);
}

//Timer method
static public void Tick(Object stateInfo)
{
    try
    {
        if (Properties.Settings.Default.BatchingMode > 0)
        {
            if (batchTime.Subtract(DateTime.Now) < TimeSpan.Zero)
            {
                batchTime = DateTime.Now.AddMinutes(Properties.Settings.Default.BatchingMode);
                Console.WriteLine("-----------------------------------------------------");
                Process();
                Console.WriteLine("Batch Process Run");
                Console.WriteLine("-----------------------------------------------------");
            }
            Console.WriteLine("{0}", DateTime.Now.ToString("h:mm:ss"));
        }
        Console.WriteLine("Pop3 Monitoring start after: {0}", batchTime.Subtract(DateTime.Now));
    }
    catch (Exception e)
    {
        throw e;
    }
}

当我注释掉我的Process()方法时,我的计时器交互每秒都能正常工作 但当我从我的Tick方法取消注释Process方法时,计时器停止工作,即Tick方法停止工作。 处理方法代码工作正常意味着没有编译和运行时错误。

1 个答案:

答案 0 :(得分:3)

您正在创建的主题几乎立即停止,无论您是否正在调用Process()。 你在线程中所做的就是启动一个计时器。实际的Tick方法正在Thread Pool的后台线程中执行。

现在,在某些时候,您的stateTimer将被垃圾收集,因为它已超出范围。此时将不再触发计时器。最有可能的是,当您致电Process()

时,这种垃圾收集的发生得更快

您可以在GC.Collect()方法中调用Tick进行测试。你会看到它在一两个滴答之后停止。

要解决此问题,请将stateTimer设为成员变量。丢失Thread内容:

class Program
{
    private static Timer _stateTimer;

    static void Main(string[] args)
    {
        _stateTimer = new Timer(Tick, null, 0, 1000);
        Console.ReadLine();
    }

    static public void Tick(Object stateInfo)
    {
        // ...
    }
}

PS:我认为这段代码是因为你一直在试验,但是如果你想重新抛出你所发现的异常,你应该使用throw;而没有任何参数:请参阅this Blog article简要说明。