我正在制作一款基于回合的silverlight游戏(纸牌游戏)。我想在两个回合之间延迟。
我试过线程。睡眠,但它会暂停我的UI。我试过使用DispatcherTimer,但它的行为很有趣。有时有效,有时跳过。
当我将间隔设置为3秒时,我的代码可以完美地使用DipatcherTimer,但是当我将间隔设置为1秒时,它开始跳过一些回合。
是否有其他方法来创建此延迟?
更新:我刚刚重启了我的窗口,它完美地工作了一段时间。一个小时后,我再次尝试,没有更改代码,它开始跳!我不明白。
您可以使用System.Threading.Timer类,但要知道它使用线程(如下所示)。计时器是在构造函数中设置的。它立即启动(第三个参数设置为0),然后每1000ms执行一次(第四个参数)。在内部,代码立即调用Dispatcher来更新UI。这样做的潜在好处是,您不会将UI线程用于可以在另一个线程中完成的繁忙工作(例如,不使用BackgroundWorker)。
using System.Windows.Controls;
using System.Threading;
namespace SLTimers
{
public partial class MainPage : UserControl
{
private Timer _tmr;
private int _counter;
public MainPage()
{
InitializeComponent();
_tmr = new Timer((state) =>
{
++_counter;
this.Dispatcher.BeginInvoke(() =>
{
txtCounter.Text = _counter.ToString();
});
}, null, 0, 1000);
}
}
}
<UserControl x:Class="SLTimers.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="txtCounter" Margin="12" FontSize="80" Text="0"/>
</Grid>
</UserControl>