C# WPF 定时器延迟加载1秒 - Task.Delay 示例
您可以使用Task.Delay方法来实现在定时器中延迟加载1秒。下面是一个示例代码:
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
public partial class MainWindow : Window
{
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
}
private async void Timer_Tick(object sender, EventArgs e)
{
timer.Stop();
// 延迟1秒
await Task.Delay(TimeSpan.FromSeconds(1));
// 在这里执行需要延迟加载的代码
timer.Start();
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
timer.Start();
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
timer.Stop();
}
}
在上述代码中,我们创建了一个DispatcherTimer对象,并设置了其间隔为1秒。在Timer_Tick事件处理程序中,我们首先停止定时器,然后使用Task.Delay方法延迟1秒。在延迟结束后,您可以在注释部分执行需要延迟加载的代码。最后,我们重新启动定时器。
请注意,Timer_Tick事件处理程序需要使用async修饰符来支持await关键字。
原文地址: https://www.cveoy.top/t/topic/o0xp 著作权归作者所有。请勿转载和采集!