C# 计时器写法

时间:2023-03-09 04:05:28
C# 计时器写法

    刚才一个交流群里有人问计时器怎么写,正好我也不太熟,就写了个demo,和大家分享一下这个是参考师傅的写的!

计时器有好多种写法,这里给大家推荐一个性能比较好的,用dispatchertimer做的,本demo是倒计时的,计时的将_seconds--改成++就可以了。不多说了,直接上代码。

1.这是界面,简单的xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Name="txt"
HorizontalAlignment="Center"
VerticalAlignment="Center"/> <Button Margin="0,0,0,50"
Content="开始倒计时"
Background="Red"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Bottom"
Click="Button_Click"/>
</Grid>

2.下面是cs代码,用的dispatchertimer,解释下Interval这个属性,它的作用是确定计时间隔,可以用秒、毫秒之类的。还有个Tick委托,该委托是在超过计时间隔时触发的,也就是Interval的时间间隔设置。

public sealed partial class MainPage : Page
{
private DispatcherTimer _countDownTimer;
private int _seconds = ; public MainPage()
{
this.InitializeComponent();
} private void Button_Click(object sender, RoutedEventArgs e)
{
this.CountDown();
} private void CountDown()
{
this._countDownTimer = new DispatcherTimer();
this._countDownTimer.Interval = TimeSpan.FromSeconds();
this._countDownTimer.Tick += this._countDownTimer_Tick;
this._countDownTimer.Start();
} private void _countDownTimer_Tick(object sender, object e)
{
this._seconds--;
this.txt.Text = this._seconds.ToString();
if (this._seconds == )
{
this.CountDownStop();
}
} private void CountDownStop() {
if (this._countDownTimer != null)
{
this._countDownTimer.Stop();
this._countDownTimer.Tick -= this._countDownTimer_Tick;
this._countDownTimer = null;
}
}
}

参考别人的写法写的,性能上还是很优异,有更好的写法欢迎评论。