C# 在C中显示下一个采样时间日期和时间而不冻结WPF表单#
我正在用WPF&C编写代码,以日期和时间格式显示下一次采样时间。 例如,如果采样时间为一分钟,当前时间为08:00-下一个采样时间应显示08:01,则一旦08:01过去,将显示下一个采样时间 我试过使用Dispatcher和sleep线程。 但是当我使用整个WPF表单时,它会冻结到下一次更新 你能帮帮我吗 代码->C# 在C中显示下一个采样时间日期和时间而不冻结WPF表单#,c#,wpf,datetime,dispatchertimer,C#,Wpf,Datetime,Dispatchertimer,我正在用WPF&C编写代码,以日期和时间格式显示下一次采样时间。 例如,如果采样时间为一分钟,当前时间为08:00-下一个采样时间应显示08:01,则一旦08:01过去,将显示下一个采样时间 我试过使用Dispatcher和sleep线程。 但是当我使用整个WPF表单时,它会冻结到下一次更新 你能帮帮我吗 代码-> public float samplingTime = 1; public MainWindow() {
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();
}
}
对于这样的问题,我会使用:
public float samplingTime = 1;
public MainWindow()
{
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
tboxSampling.Text = DateTime.Now.AddSeconds(samplingTime).ToString();
}
计时器不保证在时间间隔发生时准确执行,但保证在时间间隔发生之前不执行
您根本不应该使用
线程.睡眠
。只需修改计时器间隔或跳过计时器刻度。如果希望在不阻塞线程的情况下等待,还可以使用wait Task.Delay(…)
。但这在这里是不必要的。定时器的全部作用就是经常发射X,不需要睡觉。勾号
每隔时间间隔触发一次
,但请注意,精确度可能不是很高,因此您可以跳过秒。这似乎工作正常code
//计时器在时间窗口tboxSampling.Text=DateTime.Now.AddSeconds(samplingTime).ToString()中显示采样时间;timer.Interval=TimeSpan.FromSeconds(采样时间);timer.Tick+=定时器_Tick;timer.Start();void timer_Tick(对象发送方,EventArgs e){dtEnd=DateTime.Now.AddSeconds(samplingTime);tboxSampling.Text=dtEnd.ToString();running=true;}