问题描述
我正在用 WPF 和 C# 编写代码,以日期和时间格式显示下一个采样时间。 例如,如果采样时间为一分钟,当前时间为 08:00 - 下一次采样时间应显示为 08:01,则在 08:01 过去后显示下一次采样时间。
我尝试过使用 dispatcherTimer 和睡眠线程。 但是当我使用整个 WPF 表单时会冻结,直到下次更新。
你能帮我吗?
代码 ->
public float samplingTime = 1;
public MainWindow()
{
InitializeComponent();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
tBoxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
void timer_Tick(object sender,EventArgs e)
{
System.Threading.Thread.Sleep((int)samplingTime*1000);
tBoxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
}
解决方法
我会使用 DispatcherTimer 来解决这样的问题:
public float samplingTime = 1;
public MainWindow()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender,EventArgs e)
{
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
不保证定时器在时间间隔发生时准确执行,但保证在时间间隔发生前不执行。