GPT 给推荐的写法
using System;
using System.Windows.Forms;
namespace TimerExample
{
public partial class MainForm : Form
{
private Timer timer;
public MainForm()
{
InitializeComponent();
// 初始化定时器
timer = new Timer();
timer.Interval = 1000; // 设置定时器间隔为1秒
timer.Tick += Timer_Tick; // 添加定时器事件处理程序
}
private void Timer_Tick(object sender, EventArgs e)
{
// 在定时器事件中执行需要的操作
label1.Text = DateTime.Now.ToString();
}
private void startButton_Click(object sender, EventArgs e)
{
// 启动定时器
timer.Start();
}
private void stopButton_Click(object sender, EventArgs e)
{
// 停止定时器
timer.Stop();
}
}
}
我实测的,确实不会阻塞程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
private Timer timer = null;//定时器,用于自动隐藏
private void FormExit_Load(object sender, EventArgs e)
{
// 初始化定时器
timer = new Timer();
timer.Interval = 1000; // 设置定时器间隔为1秒
timer.Tick += Timer_Tick; // 添加定时器事件处理程序
// 启动定时器
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// 在定时器事件中执行需要的操作
notice.Text = DateTime.Now.ToString();
}
效果
![]()