2013-02-22 74 views
2

工作,我在我的程序中的线程它运行例如定时器功能为什么C#线程停止自动

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方法停止工作。 过程方法代码正在运行完美,意味着没有编译和运行时错误。

+0

你在'Process'中做了什么? – RoadBump 2013-02-22 05:08:39

+0

我的流程方法从pop3 gmail中读取邮件,然后筛选并发送httpwebrequest到我的mvc3应用程序 – Raj 2013-02-22 05:12:39

+2

流程可能比您设置的时间间隔长。因为您正在接受外部服务,请考虑增加轮询频率。 – 2013-02-22 05:15:20

回答

3

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

现在,在某个时刻,您的stateTimer将被垃圾收集,因为它已经超出范围。此时定时器将不再被触发。最有可能的,这种垃圾回收发生更快当你调用Process()

您可以通过在Tick方法调用GC.Collect()测试。你会看到它在一两次滴答后停止。

要修复它,请将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为简单的解释。

+0

Gr8精湛的感谢...从过去2天我试图解决这个问题。 .. 十分感谢 – Raj 2013-02-22 07:27:36