You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中Timer调用含return的日期方法仅生效一次的问题求助

问题分析与解决

你的问题和return无关,核心问题是定时器对象被垃圾回收:

  • 在startBtn_Click方法里,System.Timers.Timer timer是局部变量,方法执行完毕后,这个对象会被.NET垃圾回收机制回收,导致定时器只触发一次就停止工作。
  • 另外,google_date方法里的HttpWebRequest和WebResponse没有释放资源,长期调用会造成资源泄漏;而且WinForms程序里用Console.WriteLine,你大概率看不到输出结果。

修复步骤:

  1. 将定时器改为类级成员变量,避免被垃圾回收:
// 在类的顶部声明定时器变量
private System.Timers.Timer _timer;

private void startBtn_Click(object sender, EventArgs e)
{           
    _timer = new System.Timers.Timer();
    _timer.Interval = 1000;
    // 显式开启重复触发(默认值为true,声明后逻辑更清晰)
    _timer.AutoReset = true;
    _timer.Elapsed += timer_Elapsed;
    _timer.Start();
}
  1. 优化google_date方法,自动释放资源:
    用using语句确保WebRequest和WebResponse使用后自动释放,避免资源泄漏:
public string google_date()
{
    using (var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://google.com"))
    {
        using (var response = myHttpWebRequest.GetResponse())
        {
            string todaysDates = response.Headers["date"];
            return DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", 
                CultureInfo.InvariantCulture.DateTimeFormat, 
                DateTimeStyles.AssumeUniversal).ToString();            
        }
    }
}
  1. 处理跨线程UI更新(如果要显示到界面):
    定时器Elapsed事件在后台线程触发,直接更新WinForms控件会报错,需要用Invoke切换到UI线程:
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    string dateStr = google_date();
    // 示例:更新名为dateLabel的Label控件
    this.Invoke((Action)(() => {
        dateLabel.Text = "Google Date Info: " + dateStr;
        // 同时输出到控制台(需确保控制台窗口已打开)
        Console.WriteLine("Google Date Info: " + dateStr);
    }));
}

额外提示:

  • 不需要定时器时,记得在窗体关闭或停止按钮点击时调用_timer.Stop()和_timer.Dispose()释放资源。
  • 频繁请求Google服务器可能被限制,测试时可适当调大定时器间隔。

内容的提问来源于stack exchange,提问作者Jozef Stone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 20:30:46